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.
declare const id: string;
The display name of the user as a string
or null
if not set. The user can modify this value.
declare const displayName: string | null;
The primary email of the user as a string
or null
. Note that this is not necessarily unique.
declare const primaryEmail: string | null;
A boolean
indicating whether the primary email of the user is verified.
declare const primaryEmailVerified: boolean;
The profile image URL of the user as a string
or null
if no profile image is set.
declare const profileImageUrl: string | null;
The date and time when the user signed up, as a Date
.
declare const signedUpAt: Date;
A boolean
indicating whether the user has a password set.
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.
declare const clientMetadata: Json;
Read-only metadata visible on the client side. This metadata can only be modified on the server side.
declare const clientReadOnlyMetadata: Json;
The currently selected team for the user, if applicable, as a Team
object or null
if no team is selected.
declare const selectedTeam: Team | null;
Updates the user information.
Parameters
data
objectrequiredThe fields to update.
Show Properties
displayName
stringThe new display name for the user.
clientMetadata
objectCustom metadata visible to the client.
selectedTeamId
string | nullThe ID of the team to set as selected, or null
to clear selection.
profileImageUrl
string | nullThe URL of the user's new profile image, or null
to remove it.
Returns
Promise<void>
declare function update(data: {
displayName?: string;
clientMetadata?: Json;
selectedTeamId?: string | null;
profileImageUrl?: string | null;
}): Promise<void>;
await user.update({
displayName: "New Display Name",
clientMetadata: {
address: "123 Main St",
},
});
Gets the team with the specified ID.
Parameters
id
stringrequiredThe 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.
declare function getTeam(id: string): Promise<Team | null>;
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
id
stringrequiredThe 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.
declare function useTeam(id: string): Team | null;
const team = user.useTeam("teamId");
Lists all the teams the user is a member of.
Parameters
None.
Returns
Promise<Team[]>
: The list of teams.
declare function listTeams(): Promise<Team[]>;
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.
declare function useTeams(): Team[];
const teams = user.useTeams();
Sets the currently selected team for the user.
Parameters
team
Team | nullrequiredThe team to set as selected, or null
to clear selection.
Returns
Promise<void>
declare function setSelectedTeam(team: Team | null): Promise<void>;
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
data
objectrequiredThe data for creating the team.
Show Properties
displayName
stringThe display name for the team.
profileImageUrl
string | nullThe URL of the team's profile image, or null
to remove it.
Returns
Promise<Team>
: The created team.
declare function createTeam(data: {
displayName: string;
profileImageUrl?: string | null;
}): Promise<Team>;
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
team
TeamrequiredThe team to leave.
Returns
Promise<void>
declare function leaveTeam(team: Team): Promise<void>;
await user.leaveTeam(team);
Retrieves the user's profile within a specific team.
Parameters
team
TeamrequiredThe team to retrieve the profile for.
Returns
Promise<EditableTeamMemberProfile>
: The user's editable profile for the specified team.
declare function getTeamProfile(team: Team): Promise<EditableTeamMemberProfile>;
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
team
TeamrequiredThe team to retrieve the profile for.
Returns
EditableTeamMemberProfile
: The user's editable profile for the specified team.
declare function useTeamProfile(team: Team): EditableTeamMemberProfile;
const profile = user.useTeamProfile(team);
Checks if the user has a specific permission for a team.
Parameters
scope
TeamrequiredThe team to check the permission for.
permissionId
stringrequiredThe ID of the permission to check.
Returns
Promise<boolean>
: Whether the user has the specified permission.
declare function hasPermission(scope: Team, permissionId: string): Promise<boolean>;
const hasPermission = await user.hasPermission(team, "permissionId");
Retrieves a specific permission for a user within a team.
Parameters
scope
TeamrequiredThe team to retrieve the permission for.
permissionId
stringrequiredThe ID of the permission to retrieve.
options
objectAn object containing multiple properties.
Show Properties
recursive
booleanWhether to retrieve the permission recursively. Default is true
.
Returns
Promise<TeamPermission | null>
: The permission object, or null
if not found.
declare function getPermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): Promise<TeamPermission | null>;
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
scope
TeamrequiredThe team to retrieve the permission for.
permissionId
stringrequiredThe ID of the permission to retrieve.
options
objectAn object containing multiple properties.
Show Properties
recursive
booleanWhether to retrieve the permission recursively. Default is true
.
Returns
TeamPermission | null
: The permission object, or null
if not found.
declare function usePermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): TeamPermission | null;
const permission = user.usePermission(team, "read_secret_info");
Lists all permissions the user has for a specified team.
Parameters
scope
TeamrequiredThe team to list permissions for.
options
objectAn object containing multiple properties.
Show Properties
recursive
booleanWhether to list the permissions recursively. Default is true
.
Returns
Promise<TeamPermission[]>
: An array of permissions.
declare function listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>;
const permissions = await user.listPermissions(team);
Lists all permissions the user has for a specified team, used as a React hook.
Parameters
scope
TeamrequiredThe team to retrieve permissions for.
options
objectAn object containing multiple properties.
Show Properties
recursive
booleanWhether to list the permissions recursively. Default is true
.
Returns
TeamPermission[]
: An array of permissions.
declare function usePermissions(scope: Team, options?: { recursive?: boolean }): TeamPermission[];
const permissions = user.usePermissions(team);
Lists all the contact channels of the user.
Parameters
No parameters.
Returns
Promise<ContactChannel[]>
: An array of contact channels.
declare function listContactChannels(): Promise<ContactChannel[]>;
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.
declare function useContactChannels(): ContactChannel[];
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
options
objectrequiredOptions for creating the API key.
Show Properties
description
stringrequiredA human-readable description of the API key's purpose.
expiresAt
Date | nullrequiredThe date when the API key will expire. Use null for keys that don't expire.
isPublic
booleanWhether 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.
declare function createApiKey(options: {
description: string;
expiresAt: Date | null;
isPublic?: boolean;
}): Promise<UserApiKeyFirstView>;
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.
declare function listApiKeys(): Promise<UserApiKey[]>;
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.
declare function useApiKeys(): UserApiKey[];
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
data
objectrequiredThe fields required for updating the password.
Show Properties
oldPassword
stringrequiredThe current password of the user.
newPassword
stringrequiredThe new password for the user.
Returns
Promise<void>
declare function updatePassword(data: {
oldPassword: string;
newPassword: string;
}): Promise<void>;
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.
declare function getAuthHeaders(): Promise<Record<string, string>>;
// 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.
declare function getAuthJson(): Promise<{ accessToken: string | null }>;
// 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
options
objectAn object containing multiple properties.
Show Properties
redirectUrl
stringThe URL to redirect to after signing out. Defaults to the afterSignOut
URL from the Stack app's urls
object.
Returns
Promise<void>
declare function signOut(options?: { redirectUrl?: string }): Promise<void>;
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>
declare function delete(): Promise<void>;
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
.
declare const lastActiveAt: Date;
The server metadata of the user, accessible only on the server side.
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
data
objectrequiredThe fields to update.
Show Properties
displayName
stringThe new display name for the user.
primaryEmail
stringThe new primary email for the user.
primaryEmailVerified
booleanWhether the primary email is verified.
primaryEmailAuthEnabled
booleanWhether auth should be enabled for the primary email.
password
stringThe new password for the user.
selectedTeamId
string | nullThe ID of the team to set as selected, or null
to clear selection.
profileImageUrl
string | nullThe URL of the user's new profile image, or null
to remove.
clientMetadata
objectMetadata visible on the client side.
clientReadOnlyMetadata
objectMetadata that is read-only on the client but modifiable on the server side.
serverMetadata
objectMetadata only accessible and modifiable on the server side.
Returns
Promise<void>
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>;
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.
declare function listContactChannels(): Promise<ServerContactChannel[]>;
const contactChannels = await serverUser.listContactChannels();
Functionally equivalent to listContactChannels()
, but as a React hook.
declare function useContactChannels(): ContactChannel[];
Grants a specific permission to the user for a given team.
Parameters
scope
TeamrequiredThe team to grant the permission for.
permissionId
stringrequiredThe ID of the permission to grant.
Returns
Promise<void>
declare function grantPermission(scope: Team, permissionId: string): Promise<void>;
await serverUser.grantPermission(team, "read_secret_info");
Revokes a specific permission from the user for a given team.
Parameters
scope
TeamrequiredThe team to revoke the permission from.
permissionId
stringrequiredThe ID of the permission to revoke.
Returns
Promise<void>
declare function revokePermission(scope: Team, permissionId: string): Promise<void>;
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
options
objectrequiredOptions for creating the API key.
Show Properties
description
stringrequiredA human-readable description of the API key's purpose.
expiresAt
Date | nullrequiredThe date when the API key will expire. Use null for keys that don't expire.
isPublic
booleanWhether 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.
declare function createApiKey(options: {
description: string;
expiresAt: Date | null;
isPublic?: boolean;
}): Promise<UserApiKeyFirstView>;
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.
declare function listApiKeys(): Promise<UserApiKey[]>;
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.
declare function useApiKeys(): UserApiKey[];
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.