Tracking user sessions after getting new access token(s)

Hey there :wave:.

I have a React SPA that I want to do some user interaction tracking for. To do that, I need a “session ID”.

We’re using the auth0-react SDK. So, let’s say we set the cacheLocation option in the provider to localstorage. This feels like something that could serve as an ersatz session id if we encrypted it. Problem though: if the token is about to expire and we get a new one when we call getAccessTokenSilently, now this looks like two sessions, but it’s really the same session from an analytics perspective.

I’ve seen documentation about the context object in rules (referenced in this similar question), but I’m not sure if any of these options actually provide what I need. context.sessionID sounds like an obvious choice, but I’m not sure what this means:

Value is kept only if prompt=none is used in the authorization request. Note that the session ID can change after rule execution on other flows, so the value available in context.sessionID might not match the new session ID that the user will receive.

and if that would affect how viable it would make it for my usecase.

Hi @grahamalama,

Thanks for joining the Community!

The cacheLocation options determines whether the Access Token and ID Tokens will be stored in memory or local storage, but you are correct that the context.sessionID value won’t be the same if the ID Token or Access Token renewed while the user is browsing.

If you need to access information in the ID Token, you can do so by leveraging the auth0-react SDK. When you use the user objects from the useAuth0 hook, the SDK is decoding the information that is stored in the ID Token. What you could do is add a custom claim to your ID Token that you could use for session tracking:

function (user, context, callback) {
  const namespace = 'https://my-app.example.com/';
  context.idToken[namespace + 'analytics-sessionID'] = context.sessionID;
  callback(null, user, context);
}

However, you’d still have the problem that the sessionID would not be the same if the ID token expires in the same “session”.

Probably the simplest route would be to generate your own identifier for a user’s session when the user is first redirected to your app after logging in and keep it in local storage until they log out.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.