ParseError: 209 Invalid Session token

Sometimes, This error is appearing when trying to log in to my app. Is there any way to solve this issue?

Screenshot 2022-03-31 at 12.10.05

Here is my login function,

authenticate({
        onSuccess: () => {
          if (!isWeb3Enabled) {
            enableWeb3();
          }
          setIsLoading(false);
        },
        onError: (erorr) => alert(erorr),
        signingMessage: "Mintzilla Platform"
      });
useEffect(() => {
    if (isAuthenticated) {
      const sessionToken = user?.get('sessionToken');
      redirectToIronSession(sessionToken, user.id);
    }
  }, [ isAuthenticated]);
async function redirectToIronSession(sessionToken: string, userId: string) {
    const body = {
      moralisSessionToken: sessionToken,
      moralisUserId: userId,
    };
    try {
      mutateUser(
        await fetchJson('/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        })
      );
    } catch (error) {
      console.log("redirectToIronSession", error);
      if (error instanceof FetchError) {
        alert(error.data.message);
      } else {
        console.error('An unexpected error happened:', error);
      }
    }
  }

can you add some logging here to see if the sessionToken is the expected one?

1 Like

@cryptokid Thank you for your Reply.

Actually this error appears when I trying to login to my app, MetaMask ask several times for the authentication. That’s why I keep getting this error. This does not happen always. But if Metamsk shows the signature request multiple times, ParseError: 209 Invalid Session token error appears

maybe it is something related to the code that it happens to show that message so many times in metamask

1 Like

The Problem is, this does not happen always

you could add some logging maybe to see when authentication is called

1 Like

I have added some logging and identified the root of the issue, In our app, When the user switches their account, the user will be logged out and signed in with the new account at the same time.

In this scenario, when user switch their account onAccountChanged event triggers multiple times. this is the main problem for the above Invalid session Token issue

useEffect(() => {
    var unsubscribe = null;
    if (isAuthenticated && isWeb3Enabled) {
      unsubscribe = Moralis.onAccountChanged(async (accounts) => {
        console.log("onAccountChangedTriggered")
        setIsLoading(true);
        const currentUser = Moralis.User.current();
        const linked = await checkUserById(accounts, currentUser);
        if (currentUser && linked) {
          await setUserDataOnLinkStatus(accounts);
        }
      });
    }
    return () => {
      if (unsubscribe) unsubscribe();
    };  }, [isAuthenticated, isWeb3Enabled]);