# User URL: /docs/sdk/types/user Source: /vercel/path0/docs/content/docs/sdk/types/user.mdx *** title: User full: true ---------- 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](../../getting-started/users.mdx). On this page: * [CurrentUser](#currentuser) * [ServerUser](#serveruser) * [CurrentServerUser](#currentserveruser) # `CurrentUser` Use `useUser()` to get `CurrentUser` (client). Use `stackServerApp.getUser()` to get `CurrentServerUser` (server). ### Table of Contents ; //$stack-link-to:#currentuserupdate updatePassword(data): Promise; //$stack-link-to:#currentuserupdatepassword getAuthHeaders(): Promise>; //$stack-link-to:#currentusergetauthheaders getAuthJson(): Promise<{ accessToken: string | null }>; //$stack-link-to:#currentusergetauthjson signOut([options]): Promise; //$stack-link-to:#currentusersignout delete(): Promise; //$stack-link-to:#currentuserdelete getTeam(id): Promise; //$stack-link-to:#currentusergetteam // NEXT_LINE_PLATFORM react-like ⤷ useTeam(id): Team | null; //$stack-link-to:#currentuseruseteam listTeams(): Promise; //$stack-link-to:#currentuserlistteams // NEXT_LINE_PLATFORM react-like ⤷ useTeams(): Team[]; //$stack-link-to:#currentuseruseteams setSelectedTeam(team): Promise; //$stack-link-to:#currentusersetselectedteam createTeam(data): Promise; //$stack-link-to:#currentusercreateteam leaveTeam(team): Promise; //$stack-link-to:#currentuserleaveteam getTeamProfile(team): Promise; //$stack-link-to:#currentusergetteamprofile // NEXT_LINE_PLATFORM react-like ⤷ useTeamProfile(team): EditableTeamMemberProfile; //$stack-link-to:#currentuseruseteamprofile hasPermission(scope, permissionId): Promise; //$stack-link-to:#currentuserhaspermission getPermission(scope, permissionId[, options]): Promise; //$stack-link-to:#currentusergetpermission // NEXT_LINE_PLATFORM react-like ⤷ usePermission(scope, permissionId[, options]): TeamPermission | null; //$stack-link-to:#currentuserusepermission listPermissions(scope[, options]): Promise; //$stack-link-to:#currentuserlistpermissions // NEXT_LINE_PLATFORM react-like ⤷ usePermissions(scope[, options]): TeamPermission[]; //$stack-link-to:#currentuserusepermissions listContactChannels(): Promise; //$stack-link-to:#currentuserlistcontactchannels // NEXT_LINE_PLATFORM react-like ⤷ useContactChannels(): ContactChannel[]; //$stack-link-to:#currentuserusecontactchannels createApiKey(options): Promise; //$stack-link-to:#currentusercreateapikey listApiKeys(): Promise; //$stack-link-to:#currentuserlistapikeys // NEXT_LINE_PLATFORM react-like ⤷ useApiKeys(): UserApiKey[]; //$stack-link-to:#currentuseruseapikeys createCheckoutUrl(options): Promise; //$stack-link-to:#currentusercreatecheckouturl getItem(itemId): Promise; //$stack-link-to:#currentusergetitem // NEXT_LINE_PLATFORM react-like ⤷ useItem(itemId): Item; //$stack-link-to:#currentuseruseitem };`} /> The user ID as a `string`. This is the unique identifier of the user. ```typescript declare const id: string; ``` The display name of the user as a `string` or `null` if not set. The user can modify this value. ```typescript declare const displayName: string | null; ``` The primary email of the user as a `string` or `null`. Note that this is not necessarily unique. ```typescript declare const primaryEmail: string | null; ``` A `boolean` indicating whether the primary email of the user is verified. ```typescript declare const primaryEmailVerified: boolean; ``` The profile image URL of the user as a `string` or `null` if no profile image is set. ```typescript declare const profileImageUrl: string | null; ``` The date and time when the user signed up, as a `Date`. ```typescript declare const signedUpAt: Date; ``` A `boolean` indicating whether the user has a password set. ```typescript 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. ```typescript declare const clientMetadata: Json; ``` Read-only metadata visible on the client side. This metadata can only be modified on the server side. ```typescript declare const clientReadOnlyMetadata: Json; ``` The currently selected team for the user, if applicable, as a `Team` object or `null` if no team is selected. ```typescript declare const selectedTeam: Team | null; ``` Updates the user information. ### Parameters The fields to update. The new display name for the user. Custom metadata visible to the client. The ID of the team to set as selected, or `null` to clear selection. The URL of the user's new profile image, or `null` to remove it. ### Returns `Promise` ```typescript declare function update(data: { displayName?: string; clientMetadata?: Json; selectedTeamId?: string | null; profileImageUrl?: string | null; }): Promise; ``` ```typescript Updating user details await user.update({ displayName: "New Display Name", clientMetadata: { address: "123 Main St", }, }); ``` Gets the team with the specified ID. ### Parameters The ID of the team to get. ### Returns `Promise`: The team object, or `null` if the team is not found or the user is not a member of the team. ```typescript declare function getTeam(id: string): Promise; ``` ```typescript Getting a team by ID const team = await user.getTeam("teamId"); ``` {/* IF_PLATFORM next */} Gets the team with the given ID. This is the same as `getTeam` but is used as a React hook. ### Parameters 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. ```typescript declare function useTeam(id: string): Team | null; ``` ```typescript Using a team in a React component const team = user.useTeam("teamId"); ``` {/* END_PLATFORM */} Lists all the teams the user is a member of. ### Parameters None. ### Returns `Promise`: The list of teams. ```typescript declare function listTeams(): Promise; ``` ```typescript Listing all teams const teams = await user.listTeams(); ``` {/* IF_PLATFORM next */} 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. ```typescript declare function useTeams(): Team[]; ``` ```typescript Using teams in a React component const teams = user.useTeams(); ``` {/* END_PLATFORM */} Sets the currently selected team for the user. ### Parameters The team to set as selected, or `null` to clear selection. ### Returns `Promise` ```typescript declare function setSelectedTeam(team: Team | null): Promise; ``` ```typescript Setting the selected team 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 The data for creating the team. The display name for the team. The URL of the team's profile image, or `null` to remove it. ### Returns `Promise`: The created team. ```typescript declare function createTeam(data: { displayName: string; profileImageUrl?: string | null; }): Promise; ``` ```typescript Creating a new 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 The team to leave. ### Returns `Promise` ```typescript declare function leaveTeam(team: Team): Promise; ``` ```typescript Leaving a team await user.leaveTeam(team); ``` Retrieves the user's profile within a specific team. ### Parameters The team to retrieve the profile for. ### Returns `Promise`: The user's editable profile for the specified team. ```typescript declare function getTeamProfile(team: Team): Promise; ``` ```typescript Getting a team profile const profile = await user.getTeamProfile(team); ``` {/* IF_PLATFORM next */} Retrieves the user's profile within a specific team. This is the same as `getTeamProfile` but is used as a React hook. ### Parameters The team to retrieve the profile for. ### Returns `EditableTeamMemberProfile`: The user's editable profile for the specified team. ```typescript declare function useTeamProfile(team: Team): EditableTeamMemberProfile; ``` ```typescript Using a team profile in React const profile = user.useTeamProfile(team); ``` {/* END_PLATFORM */} Checks if the user has a specific permission for a team. ### Parameters The team to check the permission for. The ID of the permission to check. ### Returns `Promise`: Whether the user has the specified permission. ```typescript declare function hasPermission(scope: Team, permissionId: string): Promise; ``` ```typescript Checking user permission const hasPermission = await user.hasPermission(team, "permissionId"); ``` Retrieves a specific permission for a user within a team. ### Parameters The team to retrieve the permission for. The ID of the permission to retrieve. An object containing multiple properties. Whether to retrieve the permission recursively. Default is `true`. ### Returns `Promise`: The permission object, or `null` if not found. ```typescript declare function getPermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): Promise; ``` ```typescript Getting a permission const permission = await user.getPermission(team, "read_secret_info"); ``` {/* IF_PLATFORM next */} Retrieves a specific permission for a user within a team, used as a React hook. ### Parameters The team to retrieve the permission for. The ID of the permission to retrieve. An object containing multiple properties. Whether to retrieve the permission recursively. Default is `true`. ### Returns `TeamPermission | null`: The permission object, or `null` if not found. ```typescript declare function usePermission(scope: Team, permissionId: string, options?: { recursive?: boolean }): TeamPermission | null; ``` ```typescript Using a permission in React const permission = user.usePermission(team, "read_secret_info"); ``` {/* END_PLATFORM */} Lists all permissions the user has for a specified team. ### Parameters The team to list permissions for. An object containing multiple properties. Whether to list the permissions recursively. Default is `true`. ### Returns `Promise`: An array of permissions. ```typescript declare function listPermissions(scope: Team, options?: { recursive?: boolean }): Promise; ``` ```typescript Listing user permissions const permissions = await user.listPermissions(team); ``` {/* IF_PLATFORM next */} Lists all permissions the user has for a specified team, used as a React hook. ### Parameters The team to retrieve permissions for. An object containing multiple properties. Whether to list the permissions recursively. Default is `true`. ### Returns `TeamPermission[]`: An array of permissions. ```typescript declare function usePermissions(scope: Team, options?: { recursive?: boolean }): TeamPermission[]; ``` ```typescript Using permissions in a React component const permissions = user.usePermissions(team); ``` {/* END_PLATFORM */} Lists all the contact channels of the user. ### Parameters No parameters. ### Returns `Promise`: An array of contact channels. ```typescript declare function listContactChannels(): Promise; ``` ```typescript Listing contact channels const contactChannels = await user.listContactChannels(); ``` {/* IF_PLATFORM next */} Lists all the contact channels of the user, used as a React hook. ### Parameters No parameters. ### Returns `ContactChannel[]`: An array of contact channels. ```typescript declare function useContactChannels(): ContactChannel[]; ``` ```typescript Using contact channels in React const contactChannels = user.useContactChannels(); ``` {/* END_PLATFORM */} Creates a new API key for the user, which can be used for programmatic access to your application's backend. ### Parameters Options for creating the API key. A human-readable description of the API key's purpose. The date when the API key will expire. Use null for keys that don't expire. 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`: The newly created API key. Note that this is the only time the full API key value will be visible. ```typescript declare function createApiKey(options: { description: string; expiresAt: Date | null; isPublic?: boolean; }): Promise; ``` ```typescript Creating an API key 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`: An array of API keys belonging to the user. ```typescript declare function listApiKeys(): Promise; ``` ```typescript Listing API keys 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 ); ``` {/* IF_PLATFORM next */} 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. ```typescript declare function useApiKeys(): UserApiKey[]; ``` ```typescript Using API keys in a React component function ApiKeysList() { const user = useUser(); const apiKeys = user.useApiKeys(); return (

Your API Keys ({apiKeys.length})

    {apiKeys.map(key => (
  • {key.description} - Last four: {key.value.lastFour} {key.isValid() ? ' (valid)' : ` (invalid: ${key.whyInvalid()})`}
  • ))}
); } ```
{/* END_PLATFORM */} Updates the user's password. ### Parameters The fields required for updating the password. The current password of the user. The new password for the user. ### Returns `Promise`: Returns an error object if the operation fails, otherwise returns `void`. ```typescript declare function updatePassword(data: { oldPassword: string; newPassword: string; }): Promise; ``` ```typescript Updating user password const error = await user.updatePassword({ oldPassword: "currentPassword", newPassword: "newPassword", }); if (error) { console.error("Error updating password", error); } else { console.log("Password updated successfully"); } ``` 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers) of the CORS preflight response. ### Parameters No parameters. ### Returns `Promise>`: An object containing the authentication headers. ```typescript declare function getAuthHeaders(): Promise>; ``` ```typescript Passing auth headers to an external server // client const res = await fetch("https://api.example.com", { headers: { ...await user.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. ```typescript declare function getAuthJson(): Promise<{ accessToken: string | null }>; ``` ```typescript Passing auth tokens over an RPC call // client const res = await rpcCall(rpcEndpoint, { data: { auth: await user.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 An object containing multiple properties. The URL to redirect to after signing out. Defaults to the `afterSignOut` URL from the Stack app's `urls` object. ### Returns `Promise` ```typescript declare function signOut(options?: { redirectUrl?: string }): Promise; ``` ```typescript Signing out 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` ```typescript declare function delete(): Promise; ``` ```typescript Deleting the user await user.delete(); ``` Creates a checkout URL for purchasing a product. This method integrates with Stripe to generate a secure payment link. ### Parameters Options for creating the checkout URL. The ID of the product to purchase. ### Returns `Promise`: A URL that redirects to the Stripe checkout page for the specified product. ```typescript declare function createCheckoutUrl(options: { productId: string; }): Promise; ``` ```typescript Creating a checkout URL const checkoutUrl = await user.createCheckoutUrl({ productId: "prod_premium_plan", }); // Redirect user to checkout window.location.href = checkoutUrl; ``` Retrieves information about a specific item (such as credits, subscription quantities, etc.) for the user. ### Parameters The ID of the item to retrieve. ### Returns `Promise`: The item object containing display name, quantity, and other details. ```typescript declare function getItem(itemId: string): Promise; ``` ```typescript Getting user credits const credits = await user.getItem("credits"); console.log(`User has ${credits.quantity} credits`); console.log(`Non-negative quantity: ${credits.nonNegativeQuantity}`); ``` {/* IF_PLATFORM next */} Retrieves information about a specific item for the user, used as a React hook. ### Parameters The ID of the item to retrieve. ### Returns `Item`: The item object containing display name, quantity, and other details. ```typescript declare function useItem(itemId: string): Item; ``` ```typescript Using credits in a React component function CreditsDisplay() { const user = useUser(); const credits = user.useItem("credits"); return (

Available Credits: {credits.quantity}

Display Name: {credits.displayName}

); } ```
{/* END_PLATFORM */} ***
# `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](/docs/concepts/stack-app#client-vs-server). ### Table of Contents //$stack-link-to:#currentuser & { lastActiveAt: Date; //$stack-link-to:#serveruserlastactiveat serverMetadata: Json; //$stack-link-to:#serveruserservermetadata update(data): Promise; //$stack-link-to:#serveruserupdate listContactChannels(): Promise; //$stack-link-to:#serveruserlistcontactchannels // NEXT_LINE_PLATFORM react-like ⤷ useContactChannels(): ContactChannel[]; //$stack-link-to:#serveruserusecontactchannels grantPermission(scope, permissionId): Promise; //$stack-link-to:#serverusergrantpermission revokePermission(scope, permissionId): Promise; //$stack-link-to:#serveruserrevokepermission };`} /> The last active date and time of the user as a `Date`. ```typescript declare const lastActiveAt: Date; ``` The server metadata of the user, accessible only on the server side. ```typescript 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 The fields to update. The new display name for the user. The new primary email for the user. Whether the primary email is verified. Whether auth should be enabled for the primary email. The new password for the user. The ID of the team to set as selected, or `null` to clear selection. The URL of the user's new profile image, or `null` to remove. Metadata visible on the client side. Metadata that is read-only on the client but modifiable on the server side. Metadata only accessible and modifiable on the server side. ### Returns `Promise` ```typescript 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; ``` ```typescript Updating user details on the server 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`: An array of server-specific contact channels. ```typescript declare function listContactChannels(): Promise; ``` ```typescript Listing server-specific contact channels const contactChannels = await serverUser.listContactChannels(); ``` {/* IF_PLATFORM next */} Functionally equivalent to [`listContactChannels()`](#serveruserlistcontactchannels), but as a React hook. ```typescript declare function useContactChannels(): ContactChannel[]; ``` {/* END_PLATFORM */} Grants a specific permission to the user for a given team. ### Parameters The team to grant the permission for. The ID of the permission to grant. ### Returns `Promise` ```typescript declare function grantPermission(scope: Team, permissionId: string): Promise; ``` ```typescript Granting permission to a user await serverUser.grantPermission(team, "read_secret_info"); ``` Revokes a specific permission from the user for a given team. ### Parameters The team to revoke the permission from. The ID of the permission to revoke. ### Returns `Promise` ```typescript declare function revokePermission(scope: Team, permissionId: string): Promise; ``` ```typescript Revoking permission from a user 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 for creating the API key. A human-readable description of the API key's purpose. The date when the API key will expire. Use null for keys that don't expire. 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`: The newly created API key. Note that this is the only time the full API key value will be visible. ```typescript declare function createApiKey(options: { description: string; expiresAt: Date | null; isPublic?: boolean; }): Promise; ``` ```typescript Creating an API key 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`: An array of API keys belonging to the user. ```typescript declare function listApiKeys(): Promise; ``` ```typescript Listing API keys 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 ); ``` {/* IF_PLATFORM next */} 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. ```typescript declare function useApiKeys(): UserApiKey[]; ``` ```typescript Using API keys in a React component function ApiKeysList() { const user = useUser(); const apiKeys = user.useApiKeys(); return (

Your API Keys ({apiKeys.length})

    {apiKeys.map(key => (
  • {key.description} - Last four: {key.value.lastFour} {key.isValid() ? ' (valid)' : ` (invalid: ${key.whyInvalid()})`}
  • ))}
); } ```
{/* END_PLATFORM */} ***
# `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