User Identification

Identify and track users across sessions with persistent user IDs and properties

Human Behavior automatically identifies and tracks users across sessions using persistent user IDs and properties.

Automatic User Identification

The SDK handles user identification using cookies. A unique user ID is generated and stored in a cookie on first visit, and persists for 1 year. Initializing the SDK handles user authentication automatically.

User Identification Methods

Use this method when you have access to a tracker instance. This is the most common approach.

// After successful login/signup, identify the user with their current session
const endUserId = await tracker.identifyUser({
  userProperties: {
    email: user.email,
    name: user.name,
    plan: user.plan
  }
});

console.log('User identified with ID:', endUserId);

Returns: Promise<string> - The endUserId of the identified user

2. identifyUserGlobally() - Global Function

Use this function when you don't have direct access to a tracker instance, or for global user identification.

import { identifyUserGlobally } from 'humanbehavior-js';

// Identify user globally (works from anywhere in your app)
const endUserId = await identifyUserGlobally({
  email: user.email,
  name: user.name,
  userId: user.id,
  plan: user.plan
});

console.log('User identified globally with ID:', endUserId);

Returns: Promise<string> | null - The endUserId if successful, null if tracker not found

Framework-Specific Examples

NextAuth.js Example

// In your NextAuth configuration
import { HumanBehaviorTracker } from 'humanbehavior-js';

export default NextAuth({
  events: {
    async signIn({ user, account }) {
      // Initialize HumanBehavior tracker
      const tracker = HumanBehaviorTracker.init(process.env.NEXT_PUBLIC_HUMAN_BEHAVIOR_API_KEY);
      
      // Identify user with current endUserId
      const endUserId = await tracker.identifyUser({
        userProperties: {
          email: user.email,
          name: user.name,
          userId: user.id,
          provider: account?.provider
        }
      });
      
      console.log('User identified:', endUserId);
    }
  }
});

Firebase Auth Example

// In your Firebase auth state listener
import { HumanBehaviorTracker } from 'humanbehavior-js';

onAuthStateChanged(auth, async (user) => {
  if (user) {
    // Initialize HumanBehavior tracker
    const tracker = HumanBehaviorTracker.init(process.env.NEXT_PUBLIC_HUMAN_BEHAVIOR_API_KEY);
    
    // Identify user with current endUserId
    const endUserId = await tracker.identifyUser({
      userProperties: {
        email: user.email,
        name: user.displayName,
        image: user.photoURL,
        userId: user.uid,
        provider: user.providerData[0]?.providerId
      }
    });
    
    console.log('User identified:', endUserId);
  }
});

Google Auth Example

// In your Google Auth sign-in handler
import { HumanBehaviorTracker } from 'humanbehavior-js';

const handleGoogleSignIn = async () => {
  try {
    // Your Google Auth logic here
    const user = await signInWithGoogle();
    
    if (user) {
      // Initialize HumanBehavior tracker
      const tracker = HumanBehaviorTracker.init(process.env.NEXT_PUBLIC_HUMAN_BEHAVIOR_API_KEY);
      
      // Identify user with current endUserId
      const endUserId = await tracker.identifyUser({
        userProperties: {
          email: user.email,
          name: user.displayName,
          image: user.photoURL,
          userId: user.uid,
          provider: 'google'
        }
      });
      
      console.log('User identified:', endUserId);
    }
  } catch (error) {
    console.error('Google sign-in failed:', error);
  }
};

Client-side Identification

You can also identify users client-side after successful authentication or for client-only applications:

Placement: Call identifyUser after successful login or signup, not during page initialization.

// After successful login/signup, identify the user with their current session
const endUserId = await tracker.identifyUser({
  userProperties: {
    email: user.email,
    name: user.name,
    plan: user.plan
  }
});

console.log('User identified with ID:', endUserId);

User Logout

When a user logs out, you should clear any user-specific data. The SDK doesn't have a built-in logout method, so handle this in your authentication logic:

// Handle user logout
const handleLogout = () => {
  // Your logout logic here
  // Clear user data, redirect, etc.
  
  // Callout: The SDK automatically maintains the session ID
  // You don't need to call any specific logout method
};

Complete Example

AuthComponents.jsx
import { HumanBehaviorTracker } from 'humanbehavior-js';

function LoginForm() {
    const handleLogin = async (formData) => {   
      // ... Your authentication logic here ...

      // Upon successful authentication, identify user in the current session
      if (loginSuccessful) {
        const tracker = HumanBehaviorTracker.init(process.env.NEXT_PUBLIC_HUMAN_BEHAVIOR_API_KEY);
        
        const endUserId = await tracker.identifyUser({
          userProperties: {
            email: user.email,
            name: user.name,
            plan: 'premium'
          }
        });
        
        console.log('User successfully identified:', endUserId);
      }
    }
    
    return (
        <form onSubmit={handleLogin}>
            {/* Your form fields */}
        </form>
    );
}

function LogOutButton() {
  const handleLogout = () => {
    // ... Your logout logic here ...
    // Clear user data, redirect, etc.
  }

  return (
    <button onClick={handleLogout}>Log Out</button>
  );
}

Privacy & Segmentation

  • User properties are available in your analytics dashboard for segmentation and filtering
  • You can update user info at any time (e.g., after signup, plan change)
  • The SDK supports privacy regulations and pseudonymous IDs

Properties & Options

Property/OptionTypeDescription
endUserIdstringUnique user ID (auto-generated and stored in a cookie by default).
identifyUser()functionIdentify user with properties (returns Promise<string>).
identifyUserGlobally()functionGlobal user identification function (returns Promise).
userPropertiesobjectAny key-value pairs (e.g., email, name, plan, etc.).
cookiestringStores user ID for 365 days.

identifyUser({ userProperties }) fields:

FieldTypeDescription
AnyanyYou can provide any user property fields.
Example:
emailstringUser's email address.
namestringUser's name.
userIdstringYour internal user ID.
planstringUser's plan or segment.

Method Comparison

MethodWhen to UseReturnsCallouts
tracker.identifyUser()You have tracker instancePromise<string>Most common, direct access
identifyUserGlobally()No tracker access, global usagePromise<string or null>Works from anywhere, requires global tracker