Skip to main content
Every event carries a user ID. Until your code sets one, the ID is anonymous, and the SDK generates it. After identify, every later event carries the ID from your own system, and the dashboard shows the events of one user as one journey.

Methods

Grain Tag

Grain Tag has one method. Call it after the user logs in.
Grain Tag has no method that clears the user ID. Read Track an event.

Analytics Web

Set the user ID

identify and setUserId do the same thing for a string. Use the one that reads better in your code.
When your code knows the user at construction time, pass userId in the configuration. The first event then carries it.

Log in and log out

login sets the user ID and the authentication in one call. logout reverses both.
After logout, authStrategy is NONE, the authProvider is removed, and events carry an anonymous ID. Read Authentication.

Read the ID

getUserId returns null for an anonymous visitor. getEffectiveUserId always returns a string. Use it when you need the ID that Grain stores on the next event.

Anonymous IDs

When no user ID is set, Analytics Web generates one. The consent mode decides which kind. The daily rotating ID is computed from the date, the tenant alias, and a random seed. Two visits on different days get different IDs. Grain Tag uses the same two kinds of ID. Its auto consent mode is cookieless. Read Privacy and consent. Events before identify keep their anonymous ID. Only the events after the call carry your user ID.

Page loads

The SDK does not store your user ID across page loads. Your authentication system owns the session, so Grain does not keep a second copy. On every load, set the ID from your own session.

Servers

On a server, one client serves many users. Set the user ID before each request, and flush the event inside the request.
In a serverless function, create one client per invocation. Two requests then cannot share a user ID.
Read Node.js and servers.

React

GrainProvider takes userId in its config. When the value changes, the provider updates the client.
Read React hooks.

Rules for the client

  1. Use an ID that does not change: a database ID or a UUID. An email address changes, and a session ID changes on every session.
  2. Set the user ID on every page load, before the first event. The SDK does not store it.
  3. If the user logs out, call logout() or setUserId(null). Otherwise the next user’s events go to the previous user.
  4. Do not switch between many user IDs from one client. Grain rate-limits a source that sends many distinct IDs. Read Security.
  5. With JWT authentication, the user ID must equal the subject of the token. The API rejects an event with a different ID.
  6. On a server, set the user ID before each request, or create one client per request.
After you identify a user, you can store attributes on the user. Read User properties.