Skip to main content

Why Identify Users?

When users interact with your app anonymously, you see disconnected events. When you identify users, those events connect into a journey: Anonymous tracking:
Identified tracking:
Now you can answer questions like “What do users do before they purchase?” or “How many times did this user visit?”

Setting User ID

Set the user ID once, and all future events include it:
When to set user ID:
  • Right after user logs in
  • When app loads (if user already authenticated)
  • After successful signup

The identify() Method

identify() is an alias for setUserId() - they do the same thing:
Use whichever reads better in your code. Many analytics tools use identify(), so we support both for familiarity.

Getting Current User ID

Check which user is currently identified:
This is useful for conditionally showing features or debugging.

User ID in Initialization

You can set the user ID when creating the client:
This is convenient when you know the user ID upfront, like in server-side code or after authentication.

Clearing User ID

When users log out, clear the user ID to stop associating events with them:
Always clear user IDs on logout! Otherwise, the next user’s events will be attributed to the previous user.

Persistent vs Session-Based

The SDK doesn’t persist user IDs automatically. When the page reloads, you need to set it again:
Why not persist automatically? User sessions are managed by your authentication system (Auth0, Firebase, etc.). Grain follows your lead instead of duplicating session logic.

Best Practices

Use Stable IDs

Use IDs that don’t change, like database IDs or UUIDs:

Set Early

Identify users as early as possible to capture all their events:

Don’t Switch Frequently

Avoid switching between many different user IDs from the same client. This can trigger rate limiting. Learn more in Security.

User Properties

After identifying users, you can add properties to their profile. This is covered in detail in User Properties.

Anonymous to Identified

You can track users anonymously first, then identify them later:
Events before identification remain anonymous. Only events after setUserId() are associated with the user.

Server-Side Identification

In backend code, set the user ID for each request:
In serverless environments, create a new Grain instance per request to avoid mixing user IDs:

React Integration

When using React hooks, user identification happens automatically through the provider:
Learn more in React Integration.

Next Steps

User Properties

Add attributes to user profiles

Security

Understand user ID security