Something's gone wrong (Next JS) | Community
Skip to main content

Our product uses NextJS 13.4.9 and we are trying to integrate intercom messenger. In our _app.js we are using the useEffect below to check if the user is logged in or not (guest). What’s happening is that when he is a guest everything works well. When he logs in and opens the launcher for the first time it shows the message “Something’s gone wrong”. After a refresh everything works.

 

We have seen other related topics and they don’t work in our case. We have also used shutdown in login/logout and nothing works. Something worth mentioning is that after the login when the user clicks the launcher the Intercom’s localStorage is cleared and the intercom-session-[id] cookie as well. After a refresh all works well. Now we don’t know if this is the cause.

 

import { Intercom, shutdown } from '@intercom/messenger-js-sdk';

 

useEffect(() => {

  if (process.env.hasIntercomMessenger && process.env.intercomMessengerAppId) {

    if (user?.customerServiceIntegratorId) {

      // for logged in user

      Intercom({

        app_id: process.env.intercomMessengerAppId,

        user_id: user.customerServiceIntegratorId,

        created_at: Math.floor(new Date(user.createdAt).getTime() / 1000),

      });

    } else {

      // for guest user

      Intercom({

        app_id: process.env.intercomMessengerAppId,

      });

    }

  }

 

  return () => {

    shutdown();

  };

}, [user?.customerServiceIntegratorId]);

Hi ​@Thodoris Sean here from Intercom Engineering support 👋

The problem is likely occurring because Intercom maintains session state that can conflict when switching user contexts without a proper cleanup.

I see you’ve a shutdown method which you could try using after you check the environment variables, this would do a clean up and allow a new instance of Intercom to be created with the User id and created at. Similarly you could use the JS update method for the logged in User to update the existing Messenger instance for the User instead of creating a new instance.

Try one (or both) of those suggestions and see if that resolves the issue.


@Sean M Thank you for your reply. We did actually use the update method but we changed the logic of the useEffect which is the one below and we also used shutdown in our login and logout handlers. This eliminates any possible race conditions between clearing the localstorage of messenger and creating a new instance. Hope this helps anyone else.
 

if (appConfig?.services?.chatbot?.enabled && process.env.intercomMessengerAppId) {
Intercom({
app_id: process.env.intercomMessengerAppId,
});
}

useEffect(() => {
if (user?.customerServiceIntegratorId) {
// Update existing instance for logged in user instead of creating new one
update({
user_id: user.customerServiceIntegratorId,
created_at: Math.floor(new Date(user.createdAt).getTime() / 1000),
});
}
}, [user?.customerServiceIntegratorId]);