Skip to main content

User Identity

User identity enables targeted feature rollouts, A/B testing, and gradual rollouts based on specific users or user segments.

Why User Identity?​

Setting user identity allows you to:

  • Target specific users: Enable features for specific users or user segments
  • Gradual rollouts: Roll out features to a percentage of users
  • A/B testing: Show different variants to different users
  • Consistent experience: Same user always sees the same features

Setting Identity​

At Initialization​

Set identity when initializing the provider:

<TogglyProvider
appKey="your-app-key"
environment="production"
identity="user-123"
>
<App />
</TogglyProvider>

At Runtime​

Update identity when users log in or out:

import { useToggly } from '@ops-ai/react-native-toggly';

function AuthHandler() {
const { setIdentity } = useToggly();

const handleLogin = async (user) => {
// After successful login
await setIdentity(user.id);
};

const handleLogout = async () => {
// Clear identity on logout
await setIdentity(null);
};

return (
// ... auth UI
);
}

Groups and user claims​

For User Claims and group targeting filters, use setContext():

const { setContext } = useToggly();

await setContext({
identity: user.id,
groups: user.groups,
claims: { role: user.role, plan: user.plan },
});

See Feature filters and Evaluated-signed.

How It Works​

  1. Identity is sent with flag requests: When fetching flags, the identity is included
  2. Server evaluates targeting rules: Toggly evaluates your targeting rules against the identity
  3. Consistent results: The same identity always receives the same flag values
  4. Cache per identity: Flag cache is invalidated when identity changes

Example Flows​

Login Flow​

function LoginScreen() {
const { setIdentity } = useToggly();
const [loading, setLoading] = useState(false);

const handleLogin = async (credentials) => {
setLoading(true);
try {
// 1. Authenticate user
const response = await authAPI.login(credentials);

// 2. Set Toggly identity
await setIdentity(response.user.id);

// 3. Navigate to home
navigation.navigate('Home');
} catch (error) {
Alert.alert('Login failed', error.message);
} finally {
setLoading(false);
}
};

return (
// ... login form
);
}

Logout Flow​

function SettingsScreen() {
const { setIdentity } = useToggly();

const handleLogout = async () => {
try {
// 1. Clear Toggly identity first
await setIdentity(null);

// 2. Clear auth tokens
await authAPI.logout();

// 3. Navigate to login
navigation.reset({ routes: [{ name: 'Login' }] });
} catch (error) {
console.error('Logout error:', error);
}
};

return (
<Button title="Logout" onPress={handleLogout} />
);
}

Account Switching​

function AccountSwitcher() {
const { setIdentity } = useToggly();
const [accounts, setAccounts] = useState([]);
const [currentAccount, setCurrentAccount] = useState(null);

const switchAccount = async (account) => {
// Update identity when switching accounts
await setIdentity(account.id);
setCurrentAccount(account);
};

return (
<View>
{accounts.map((account) => (
<TouchableOpacity
key={account.id}
onPress={() => switchAccount(account)}
>
<Text>{account.name}</Text>
{currentAccount?.id === account.id && <CheckIcon />}
</TouchableOpacity>
))}
</View>
);
}

Identity Types​

User ID​

Most common - use the user's unique identifier:

await setIdentity(user.id); // e.g., "user-12345"

Email Hash​

If you prefer not to send raw emails:

import { createHash } from 'crypto';

const emailHash = createHash('sha256')
.update(user.email.toLowerCase())
.digest('hex');

await setIdentity(emailHash);

Anonymous ID​

For users who haven't logged in:

import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';

// Generate and persist an anonymous ID
const getAnonymousId = async () => {
let id = await AsyncStorage.getItem('anonymous_id');
if (!id) {
id = uuidv4();
await AsyncStorage.setItem('anonymous_id', id);
}
return id;
};

// Use anonymous ID until login
const anonymousId = await getAnonymousId();
await setIdentity(anonymousId);

Entity context vs user identity​

setIdentity / groups / claims are user context for rollouts and User Claims filters. Do not attach page-entity attributes here.

Entity kinds use local registerContext and per-widget context. See Entity context and Entity & page context. Mobile clients never PUT schemas.

Targeting in Toggly.io​

In the Toggly.io dashboard, you can create targeting rules based on identity:

Percentage Rollout​

Roll out a feature to a percentage of users:

  • Feature enabled for 10% of users
  • Identity is hashed to determine if user is in the percentage

User Segments​

Target specific users or groups:

  • Beta testers: identity IN [user-1, user-2, user-3]
  • Enterprise users: Based on identity patterns

A/B Testing​

Split traffic between variants:

  • Variant A: 50% of users
  • Variant B: 50% of users
  • Same user always sees the same variant

Session Caching​

Session Caching

When using user identifiers, evaluated features are cached per user for 30 minutes by default on a sliding window. This ensures users don't see feature changes mid-session, which could be confusing.

The session length is configurable in your Toggly.io App Settings.

Best Practices​

  1. Use stable identifiers - User IDs that don't change
  2. Set identity early - Before rendering feature-gated content
  3. Clear on logout - Always call setIdentity(null) on logout
  4. Handle anonymous users - Generate and persist an anonymous ID
  5. Don't use PII directly - Hash sensitive data like emails
  6. Consider identity persistence - Store identity for faster app startup