Issue
You might encounter a race condition where Segment track events fire on a redirected page before the identify() call completes, resulting in events that are missing the proper userId. This often happens during login flows when the browser executes page scripts faster than the identity data can be persisted and retrieved.
Product
Segment Analytics.js
Cause
This timing issue occurs because the client-side library may not have finished processing the identity call before the next page loads and triggers new events. Because the identity state isn't yet available in local storage or cookies, the initial events on the new page are sent without the authenticated user's ID.
Resolution
To ensure the user identity is available immediately upon page load, you can use one of the following methods:
Method 1: Set the user ID cookie server-side
- Configure your server to set the
ajs_user_idcookie during the redirect process. - Ensure the cookie is set on your top-level domain (e.g.,
.yourdomain.com) and uses the correct path (/) so it is accessible across your site. - Update your Analytics.js configuration to prioritize cookies in the storage priority settings. This ensures the library reads the server-set cookie before checking local storage.
Method 2: Use the Querystring API
- Append the user ID to your redirect URL as a parameter, for example:
?ajs_uid=USER_ID. - When the redirected page loads, Analytics.js will automatically detect this parameter and trigger an identify() call before other events fire.
Additional Information
- Client-side persistence - Storage Priority
- Managing identity in Analytics.js - Refreshing the Anonymous ID
- Querystring API
Setting the ajs_user_id server-side does not update the ajs_anonymous_id. This is expected behavior and ensures that Segment can still properly stitch together the user's previous anonymous activity with their newly identified actions.