User

This is a detailed reference for the User object. If you're looking for a more high-level overview, please refer to our guide on users here.

On this page:

CurrentUser

You can call useUser() or stackServerApp.getUser() to get the CurrentUser object.

Table of Contents

The user ID as a string. This is the unique identifier of the user.

Type Definition
declare const id: string;

The display name of the user as a string or null if not set. The user can modify this value.

Type Definition
declare const displayName: string | null;

The primary email of the user as a string or null. Note that this is not necessarily unique.

Type Definition
declare const primaryEmail: string | null;

A boolean indicating whether the primary email of the user is verified.

Type Definition
declare const primaryEmailVerified: boolean;

The profile image URL of the user as a string or null if no profile image is set.

Type Definition
declare const profileImageUrl: string | null;

The date and time when the user signed up, as a Date.

Type Definition
declare const signedUpAt: Date;

A boolean indicating whether the user has a password set.

Type Definition
declare const hasPassword: boolean;

The client metadata of the user as an object. This metadata is visible on the client side but should not contain sensitive or server-only information.

Type Definition
declare const clientMetadata: Json;

Read-only metadata visible on the client side. This metadata can only be modified on the server side.

Type Definition
declare const clientReadOnlyMetadata: Json;

The currently selected team for the user, if applicable, as a Team object or null if no team is selected.

Type Definition
declare const selectedTeam: Team | null;

Updates the user information.

Parameters

dataobjectrequired

The fields to update.

Show Properties
displayNamestring

The new display name for the user.

clientMetadataobject

Custom metadata visible to the client.

selectedTeamIdstring | null

The ID of the team to set as selected, or null to clear selection.

profileImageUrlstring | null

The URL of the user's new profile image, or null to remove it.

Returns

Promise<void>

Signature
declare function update(data: {
  displayName?: string;
  clientMetadata?: Json;
  selectedTeamId?: string | null;
  profileImageUrl?: string | null;
}): Promise<void>;
Examples
await user.update({
  displayName: "New Display Name",
  clientMetadata: {
    address: "123 Main St",
  },
});

Gets the team with the specified ID.

Parameters

idstringrequired

The ID of the team to get.

Returns

Promise<Team | null>: The team object, or null if the team is not found or the user is not a member of the team.

Signature
declare function getTeam(id: string): Promise<Team | null>;
Examples
const team = await user.getTeam("teamId");

Gets the team with the given ID. This is the same as getTeam but is used as a React hook.

Parameters

idstringrequired

The ID of the team to get.

Returns

Team | null: The team object, or null if the team is not found or the user is not a member of the team.

Signature
declare function useTeam(id: string): Team | null;
Examples
const team = user.useTeam("teamId");

Lists all the teams the user is a member of.

Parameters

None.

Returns

Promise<Team[]>: The list of teams.

Signature
declare function listTeams(): Promise<Team[]>;
Examples
const teams = await user.listTeams();

Lists all the teams the user is a member of. This is the same as listTeams but is used as a React hook.

Parameters

None.

Returns

Team[]: The list of teams.

Signature
declare function useTeams(): Team[];
Examples
const teams = user.useTeams();

Sets the currently selected team for the user.

Parameters

teamTeam | nullrequired

The team to set as selected, or null to clear selection.

Returns

Promise<void>

Signature
declare function setSelectedTeam(team: Team | null): Promise<void>;
Examples
const team = await user.getTeam("team_id_123");
await user.setSelectedTeam(team);

Creates a new team for the user. The user will be added to the team and given creator permissions.

Note: If client-side team creation is disabled in the Stack dashboard, this will throw an error.

Parameters

dataobjectrequired

The data for creating the team.

Show Properties
displayNamestring

The display name for the team.

profileImageUrlstring | null

The URL of the team's profile image, or null to remove it.

Returns

Promise<Team>: The created team.

Signature
declare function createTeam(data: {
  displayName: string;
  profileImageUrl?: string | null;
}): Promise<Team>;
Examples
const team = await user.createTeam({
  displayName: "New Team",
  profileImageUrl: "https://example.com/profile.jpg",
});

Allows the user to leave a team. If the user is not a member of the team, this will throw an error.

Parameters

teamTeamrequired

The team to leave.

Returns

Promise<void>

Signature
declare function leaveTeam(team: Team): Promise<void>;
Examples
await user.leaveTeam(team);

Retrieves the user's profile within a specific team.

Parameters

teamTeamrequired

The team to retrieve the profile for.

Returns

Promise<EditableTeamMemberProfile>: The user's editable profile for the specified team.

Signature
declare function getTeamProfile(team: Team): Promise<EditableTeamMemberProfile>;
Examples
const profile = await user.getTeamProfile(team);

Retrieves the user's profile within a specific team. This is the same as getTeamProfile but is used as a React hook.

Parameters

teamTeamrequired

The team to retrieve the profile for.

Returns

EditableTeamMemberProfile: The user's editable profile for the specified team.

Signature
declare function useTeamProfile(team: Team): EditableTeamMemberProfile;
Examples
const profile = user.useTeamProfile(team);

Checks if the user has a specific permission for a team.

Parameters

scopeTeamrequired

The team to check the permission for.

permissionIdstringrequired

The ID of the permission to check.

Returns

Promise<boolean>: Whether the user has the specified permission.

Signature
declare function hasPermission(scope: Team, permissionId: string): Promise<boolean>;
Examples
const hasPermission = await user.hasPermission(team, "permissionId");

Retrieves a specific permission for a user within a team.

Parameters

scopeTeamrequired

The team to retrieve the permission for.

permissionIdstringrequired

The ID of the permission to retrieve.

optionsobject

An object containing multiple properties.

Show Properties
recursiveboolean

Whether to retrieve the permission recursively. Default is true.

Returns

Promise<TeamPermission | null>: The permission object, or null if not found.

Signature
declare function getPermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): Promise<TeamPermission | null>;
Examples
const permission = await user.getPermission(team, "read_secret_info");

Retrieves a specific permission for a user within a team, used as a React hook.

Parameters

scopeTeamrequired

The team to retrieve the permission for.

permissionIdstringrequired

The ID of the permission to retrieve.

optionsobject

An object containing multiple properties.

Show Properties
recursiveboolean

Whether to retrieve the permission recursively. Default is true.

Returns

TeamPermission | null: The permission object, or null if not found.

Signature
declare function usePermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): TeamPermission | null;
Examples
const permission = user.usePermission(team, "read_secret_info");

Lists all permissions the user has for a specified team.

Parameters

scopeTeamrequired

The team to list permissions for.

optionsobject

An object containing multiple properties.

Show Properties
recursiveboolean

Whether to list the permissions recursively. Default is true.

Returns

Promise<TeamPermission[]>: An array of permissions.

Signature
declare function listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>;
Examples
const permissions = await user.listPermissions(team);

Lists all permissions the user has for a specified team, used as a React hook.

Parameters

scopeTeamrequired

The team to retrieve permissions for.

optionsobject

An object containing multiple properties.

Show Properties
recursiveboolean

Whether to list the permissions recursively. Default is true.

Returns

TeamPermission[]: An array of permissions.

Signature
declare function usePermissions(scope: Team, options?: { recursive?: boolean }): TeamPermission[];
Examples
const permissions = user.usePermissions(team);

Lists all the contact channels of the user.

Parameters

No parameters.

Returns

Promise<ContactChannel[]>: An array of contact channels.

Signature
declare function listContactChannels(): Promise<ContactChannel[]>;
Examples
const contactChannels = await user.listContactChannels();

Lists all the contact channels of the user, used as a React hook.

Parameters

No parameters.

Returns

ContactChannel[]: An array of contact channels.

Signature
declare function useContactChannels(): ContactChannel[];
Examples
const contactChannels = user.useContactChannels();

Creates a new API key for the user, which can be used for programmatic access to your application's backend.

Parameters

optionsobjectrequired

Options for creating the API key.

Show Properties
descriptionstringrequired

A human-readable description of the API key's purpose.

expiresAtDate | nullrequired

The date when the API key will expire. Use null for keys that don't expire.

isPublicboolean

Whether the API key is public. Defaults to false.

  • Secret API Keys (default) begin with sk_ and are monitored by Stack Auth's secret scanner, which can revoke them if detected in public code repositories.
  • Public API Keys begin with pk_ and are designed for client-side code where exposure is not a concern.

Returns

Promise<UserApiKeyFirstView>: The newly created API key. Note that this is the only time the full API key value will be visible.

Signature
declare function createApiKey(options: {
  description: string;
  expiresAt: Date | null;
  isPublic?: boolean;
}): Promise<UserApiKeyFirstView>;
Examples
const apiKey = await user.createApiKey({
  description: "Backend integration",
  expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), // 90 days
  isPublic: false,
});

// Save the API key value securely, as it won't be retrievable later
console.log("API Key:", apiKey.value);

Lists all API keys that belong to the user.

Parameters

None.

Returns

Promise<UserApiKey[]>: An array of API keys belonging to the user.

Signature
declare function listApiKeys(): Promise<UserApiKey[]>;
Examples
const apiKeys = await user.listApiKeys();
console.log(`You have ${apiKeys.length} API keys`);

// Find keys that are about to expire
const soonToExpire = apiKeys.filter(key => 
  key.expiresAt && key.expiresAt.getTime() - Date.now() < 7 * 24 * 60 * 60 * 1000
);

Lists all API keys that belong to the user, used as a React hook.

Parameters

None.

Returns

UserApiKey[]: An array of API keys belonging to the user.

Signature
declare function useApiKeys(): UserApiKey[];
Examples
function ApiKeysList() {
  const user = useUser();
  const apiKeys = user.useApiKeys();
  
  return (
    <div>
      <h2>Your API Keys ({apiKeys.length})</h2>
      <ul>
        {apiKeys.map(key => (
          <li key={key.id}>
            {key.description} - Last four: {key.value.lastFour}
            {key.isValid() ? ' (valid)' : ` (invalid: ${key.whyInvalid()})`}
          </li>
        ))}
      </ul>
    </div>
  );
}

Updates the user's password.

Parameters

dataobjectrequired

The fields required for updating the password.

Show Properties
oldPasswordstringrequired

The current password of the user.

newPasswordstringrequired

The new password for the user.

Returns

Promise<void>

Signature
declare function updatePassword(data: {
  oldPassword: string;
  newPassword: string;
}): Promise<void>;
Examples
const result = await user.updatePassword({
  oldPassword: "currentPassword",
  newPassword: "newPassword",
});
if (result.status === "error") {
  console.error("Error updating password", result.error);
} else {
  console.log("Password updated");
}

Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin requests. Similar to getAuthJson, but specifically for HTTP requests.

If you are using tokenStore: "cookie", you don't need this for same-origin requests. However, most browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead if the client and server are on different origins.

This function returns a header object that can be used with fetch or other HTTP request libraries to send authenticated requests.

On the server, you can then pass in the Request object to the tokenStore option of your Stack app. Please note that CORS does not allow most headers by default, so you must include x-stack-auth in the Access-Control-Allow-Headers header of the CORS preflight response.

Parameters

No parameters.

Returns

Promise<Record<string, string>>: An object containing the authentication headers.

Signature
declare function getAuthHeaders(): Promise<Record<string, string>>;
Examples
// client
const res = await fetch("https://api.example.com", {
  headers: {
    ...await stackApp.getAuthHeaders()
    // you can also add your own headers here
  },
});

// server
function handleRequest(req: Request) {
  const user = await stackServerApp.getUser({ tokenStore: req });
  return new Response("Welcome, " + user.displayName);
}

Creates a JSON-serializable object containing the information to authenticate a user on an external server.

While getAuthHeaders is the recommended way to send authentication tokens over HTTP, your app may use a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.

On the server, you can pass in this token object into the tokenStore option to fetch user details.

Parameters

No parameters.

Returns

Promise<{ accessToken: string | null }>: An object containing the access token.

Signature
declare function getAuthJson(): Promise<{ accessToken: string | null }>;
Examples
// client
const res = await rpcCall(rpcEndpoint, {
  data: {
    auth: await stackApp.getAuthJson(),
  },
});

// server
function handleRequest(data) {
  const user = await stackServerApp.getUser({ tokenStore: data.auth });
  return new Response("Welcome, " + user.displayName);
}

Signs out the user and clears the session.

Parameters

optionsobject

An object containing multiple properties.

Show Properties
redirectUrlstring

The URL to redirect to after signing out. Defaults to the afterSignOut URL from the Stack app's urls object.

Returns

Promise<void>

Signature
declare function signOut(options?: { redirectUrl?: string }): Promise<void>;
Examples
await user.signOut();

Deletes the user. This action is irreversible and can only be used if client-side user deletion is enabled in the Stack dashboard.

Parameters

No parameters.

Returns

Promise<void>

Signature
declare function delete(): Promise<void>;
Examples
await user.delete();

ServerUser

The ServerUser object contains most CurrentUser properties and methods with the exception of those that require an active session (getAuthJson and signOut). It also contains some additional functions that require server-level permissions.

Table of Contents

The last active date and time of the user as a Date.

Type Definition
declare const lastActiveAt: Date;

The server metadata of the user, accessible only on the server side.

Type Definition
declare const serverMetadata: Json;

Updates the user's information on the server side. This is similar to the CurrentUser.update() method but includes additional capabilities, such as updating server metadata or setting a new password directly.

Parameters

dataobjectrequired

The fields to update.

Show Properties
displayNamestring

The new display name for the user.

primaryEmailstring

The new primary email for the user.

primaryEmailVerifiedboolean

Whether the primary email is verified.

primaryEmailAuthEnabledboolean

Whether auth should be enabled for the primary email.

passwordstring

The new password for the user.

selectedTeamIdstring | null

The ID of the team to set as selected, or null to clear selection.

profileImageUrlstring | null

The URL of the user's new profile image, or null to remove.

clientMetadataobject

Metadata visible on the client side.

clientReadOnlyMetadataobject

Metadata that is read-only on the client but modifiable on the server side.

serverMetadataobject

Metadata only accessible and modifiable on the server side.

Returns

Promise<void>

Signature
declare function update(data: {
  displayName?: string;
  profileImageUrl?: string | null;
  primaryEmail?: string,
  primaryEmailVerified?: boolean,
  primaryEmailAuthEnabled?: boolean,
  password?: string;
  selectedTeamId?: string | null;
  clientMetadata?: Json;
  clientReadOnlyMetadata?: Json;
  serverMetadata?: Json;
}): Promise<void>;
Examples
await serverUser.update({
  displayName: "Updated Display Name",
  password: "newSecurePassword",
  serverMetadata: {
    internalNote: "Confidential information",
  },
});

Lists all the contact channels of the user on the server side. This is similar to CurrentUser.listContactChannels() but returns a list of ServerContactChannel objects, which may include additional server-only details.

Parameters

No parameters.

Returns

Promise<ServerContactChannel[]>: An array of server-specific contact channels.

Signature
declare function listContactChannels(): Promise<ServerContactChannel[]>;
Examples
const contactChannels = await serverUser.listContactChannels();
Snippet not found: ../../snippets/use-on-server-callout.mdx

Functionally equivalent to listContactChannels(), but as a React hook.

Signature
declare function useContactChannels(): ContactChannel[];

Grants a specific permission to the user for a given team.

Parameters

scopeTeamrequired

The team to grant the permission for.

permissionIdstringrequired

The ID of the permission to grant.

Returns

Promise<void>

Signature
declare function grantPermission(scope: Team, permissionId: string): Promise<void>;
Examples
await serverUser.grantPermission(team, "read_secret_info");

Revokes a specific permission from the user for a given team.

Parameters

scopeTeamrequired

The team to revoke the permission from.

permissionIdstringrequired

The ID of the permission to revoke.

Returns

Promise<void>

Signature
declare function revokePermission(scope: Team, permissionId: string): Promise<void>;
Examples
await serverUser.revokePermission(team, "read_secret_info");

Creates a new API key for the user, which can be used for programmatic access to your application's backend.

Parameters

optionsobjectrequired

Options for creating the API key.

Show Properties
descriptionstringrequired

A human-readable description of the API key's purpose.

expiresAtDate | nullrequired

The date when the API key will expire. Use null for keys that don't expire.

isPublicboolean

Whether the API key is public. Defaults to false.

  • Secret API Keys (default) begin with sk_ and are monitored by Stack Auth's secret scanner, which can revoke them if detected in public code repositories.
  • Public API Keys begin with pk_ and are designed for client-side code where exposure is not a concern.

Returns

Promise<UserApiKeyFirstView>: The newly created API key. Note that this is the only time the full API key value will be visible.

Signature
declare function createApiKey(options: {
  description: string;
  expiresAt: Date | null;
  isPublic?: boolean;
}): Promise<UserApiKeyFirstView>;
Examples
const apiKey = await serverUser.createApiKey({
  description: "Backend integration",
  expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), // 90 days
  isPublic: false,
});

// Save the API key value securely, as it won't be retrievable later
console.log("API Key:", apiKey.value);

Lists all API keys that belong to the user.

Parameters

None.

Returns

Promise<UserApiKey[]>: An array of API keys belonging to the user.

Signature
declare function listApiKeys(): Promise<UserApiKey[]>;
Examples
const apiKeys = await serverUser.listApiKeys();
console.log(`You have ${apiKeys.length} API keys`);

// Find keys that are about to expire
const soonToExpire = apiKeys.filter(key => 
  key.expiresAt && key.expiresAt.getTime() - Date.now() < 7 * 24 * 60 * 60 * 1000
);

Lists all API keys that belong to the user, used as a React hook.

Parameters

None.

Returns

UserApiKey[]: An array of API keys belonging to the user.

Signature
declare function useApiKeys(): UserApiKey[];
Examples
function ApiKeysList() {
  const user = useUser();
  const apiKeys = user.useApiKeys();
  
  return (
    <div>
      <h2>Your API Keys ({apiKeys.length})</h2>
      <ul>
        {apiKeys.map(key => (
          <li key={key.id}>
            {key.description} - Last four: {key.value.lastFour}
            {key.isValid() ? ' (valid)' : ` (invalid: ${key.whyInvalid()})`}
          </li>
        ))}
      </ul>
    </div>
  );
}

CurrentServerUser

The CurrentServerUser object combines all the properties and methods of both CurrentUser and ServerUser. You can obtain a CurrentServerUser by calling stackServerApp.getUser() on the server side.

Table of Contents

Stack Auth AI

Documentation assistant

Experimental: AI responses may not always be accurate—please verify important details.

For the most accurate information, please join our Discord or email us.

How can I help?

Ask me about Stack Auth while you browse the docs.