Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

User

The User object holds all of the information for a single user of your application and provides a set of methods to manage their account. Each user has a unique authentication identifier which might be their email address, phone number, or a username.

A user can be contacted at their primary email address or primary phone number. They can have more than one registered email address, but only one of them will be their primary email address. This goes for phone numbers as well; a user can have more than one, but only one phone number will be their primary. At the same time, a user can also have one or more external accounts by connecting to OAuth providers such as Google, Apple, Facebook, and many more.

Finally, a User object holds profile data like the user's name, profile picture, and a set of metadata that can be used internally to store arbitrary information. The metadata are split into publicMetadata and privateMetadata. Both types are set from the Backend API(opens in a new tab), but public metadata can also be accessed from the Frontend API(opens in a new tab).

The ClerkJS SDK provides some helper methods on the User object to help retrieve and update user information and authentication status.

Properties

NameTypeDescription
idstringA unique identifier for the user.
firstNamestring | nullThe user's first name.
lastNamestring | nullThe user's last name.
fullNamestring | nullThe user's full name.
usernamestring | nullThe user's username.
hasImagebooleanA getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns false if Clerk is displaying an avatar for the user.
profileImageUrl (deprecated)string | nullDeprecated in favor of image_url.
imageUrlstringHolds the default avatar or user's uploaded profile image. Compatible with Clerk's Image Optimization.
primaryEmailAddressEmailAddress | nullInformation about the user's primary email address.
primaryEmailAddressIdstring | nullThe unique identifier for the EmailAddress that the user has set as primary.
emailAddressesEmailAddress[]An array of all the EmailAddress objects associated with the user. Includes the primary.
hasVerifiedEmailAddressbooleanA getter boolean to check if the user has verified an email address.
primaryPhoneNumberPhoneNumber | nullInformation about the user's primary phone number.
primaryPhoneNumberIdstring | nullThe unique identifier for the PhoneNumber that the user has set as primary.
phoneNumbersPhoneNumber[]An array of all the PhoneNumber objects associated with the user. Includes the primary.
hasVerifiedPhoneNumberbooleanA getter boolean to check if the user has verified a phone number.
primaryWeb3WalletIdstring | nullThe unique identifier for the Web3Wallet that the user signed up with.
primaryWeb3WalletWeb3Wallet | nullThe Web3Wallet that the user signed up with.
web3WalletsWeb3Wallet[]An array of all the Web3Wallet objects associated with the user. Includes the primary.
externalAccountsExternalAccount[]An array of all the ExternalAccount objects associated with the user via OAuth.
Note: This includes both verified & unverified external accounts.
verifiedExternalAccountsExternalAccount[]A getter for the user's list of verified external accounts.
unverifiedExternalAccountsExternalAccount[]A getter for the user's list of unverified external accounts.
samlAccountsSamlAccount[]An experimental list of saml accounts associated with the user.
organizationMembershipsOrganizationMembership[]A list of OrganizationMemberships representing the list of organizations the user is member with.
passwordEnabledbooleanA boolean indicating whether the user has a password on their account.
totpEnabledbooleanA boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator ap
twoFactorEnabledbooleanA boolean indicating whether the user has enabled two-factor authentication.
backupCodeEnabledbooleanA boolean indicating whether the user has enabled Backup codes.
createOrganizationEnabledbooleanA boolean indicating whether the organization creation is enabled for the user or not.
deleteSelfEnabledbooleanA boolean indicating whether the user is able to delete their own account or not.
publicMetadata{[string]: any} | nullMetadata that can be read from the Frontend API and Backend API and can be set only from the Backend API .
privateMetadata{[string]: any} | nullMetadata that can be read and set only from the Backend API.
unsafeMetadata{[string]: any} | nullMetadata that can be read and set from the Frontend API. One common use case for this attribute is to implement custom fields that will be attached to the User object.
Please note that there is also an unsafeMetadata attribute in the SignUp object. The value of that field will be automatically copied to the user's unsafe metadata once the sign up is complete.
lastSignInAtDateDate when the user last signed in. May be empty if the user has never signed in.
createdAtDateDate when the user was first created.
updatedAtDateDate of the last time the user was updated.

Methods

update()

Updates the user's attributes. Use this method to save information you collected about the user.

The appropriate settings must be enabled in the Clerk Dashboard for the user to be able to update their attributes. For example, if you want to use the update({ firstName }) method, you must enable the Name setting. It can be found in the the Clerk Dashboard under User & Authentication > Email, Phone, Username > Personal information(opens in a new tab).

function update: (params: UpdateUserParams) => Promise<User>;

UpdateUserParams

All props below are optional.

NameTypeDescription
usernamestringThe user's username.
password (deprecated)stringThe user's password.
This property is deprecated. This will be removed in the next major version (Core 2). Please use updatePassword(params) instead.
firstNamestringThe user's first name.
lastNamestringThe user's last name.
primaryEmailAddressIdstringThe unique identifier for the EmailAddress that the user has set as primary.
primaryPhoneNumberIdstringThe unique identifier for the PhoneNumber that the user has set as primary.
primaryWeb3WalletIdstringThe unique identifier for the Web3Wallet that the user signed up with.
unsafeMetadata{[string]: any} | nullMetadata that can be read and set from the Frontend API. One common use case for this attribute is to implement custom fields that will be attached to the User object.
Please note that there is also an unsafeMetadata attribute in the SignUp object. The value of that field will be automatically copied to the user's unsafe metadata once the sign up is complete.

update() returns

TypeDescription
Promise<User>This method returns a Promise which resolves with the current User object.

update() example

In the following example, the user's first name is updated to "Test".

import Clerk from '@clerk/clerk-js'; // Initialize Clerk with your Clerk publishable key const clerk = new Clerk(`{{pub_key}}`); await clerk.load(); if (!clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector<HTMLDivElement>( "#app" )!.innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector<HTMLDivElement>("#sign-in")!; clerk.mountSignIn(signInComponent, {}); } else { await clerk.user.update({ firstName: "Test" }); }
<script> // Get your publishable key and frontend API URL from the Clerk Dashboard const clerkPublishableKey = `{{pub_key}}`; const frontendApi = 'https://[your-domain].clerk.accounts.dev'; const version = '@latest'; // Set to appropriate version // Creates asynchronous script const script = document.createElement('script'); script.setAttribute('data-clerk-frontend-api', frontendApi); script.setAttribute('data-clerk-publishable-key', clerkPublishableKey); script.async = true; script.src = `${frontendApi}/npm/@clerk/clerk-js${version}/dist/clerk.browser.js`; // Adds listener to initialize ClerkJS after it's loaded script.addEventListener('load', async function () { await window.Clerk.load(); if (!window.Clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector("#app").innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector("#sign-in"); window.Clerk.mountSignIn(signInComponent, {}); } else { await window.Clerk.user.update({ firstName: "Test" }) } }); document.body.appendChild(script); </script>

delete()

Deletes the current user.

function delete: () => Promise<void>;

delete() example

import Clerk from '@clerk/clerk-js'; // Initialize Clerk with your Clerk publishable key const clerk = new Clerk(`{{pub_key}}`); await clerk.load(); if (!clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector<HTMLDivElement>( "#app" )!.innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector<HTMLDivElement>("#sign-in")!; clerk.mountSignIn(signInComponent, {}); } else { await clerk.user.delete(); }
<script> // Get your publishable key and frontend API URL from the Clerk Dashboard const clerkPublishableKey = `{{pub_key}}`; const frontendApi = 'https://[your-domain].clerk.accounts.dev'; const version = '@latest'; // Set to appropriate version // Creates asynchronous script const script = document.createElement('script'); script.setAttribute('data-clerk-frontend-api', frontendApi); script.setAttribute('data-clerk-publishable-key', clerkPublishableKey); script.async = true; script.src = `${frontendApi}/npm/@clerk/clerk-js${version}/dist/clerk.browser.js`; // Adds listener to initialize ClerkJS after it's loaded script.addEventListener('load', async function () { await window.Clerk.load(); if (!window.Clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector("#app").innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector("#sign-in"); window.Clerk.mountSignIn(signInComponent, {}); } else { await window.Clerk.user.delete(); } }); document.body.appendChild(script); </script>

setProfileImage()

Adds the user's profile image or replaces it if one already exists. This method will upload an image and associate it with the user.

function setProfileImage: (params: SetProfileImageParams) => Promise<ImageResource>;

SetProfileImageParams

NameTypeDescription
fileBlob | File | string | nullThe file to set as the user's profile image.

setProfileImage() returns

TypeDescription
Promise<ImageResource>This method returns a Promise which resolves with the current uploaded image.
ImageResource
NameTypeDescription
id?stringThe unique identifier of the image.
namestring | nullThe name of the image.
publicUrlstring | nullThe publically accessible url for the image.

getSessions()

Retrieves all active sessions for this user. This method uses a cache so a network request will only be triggered only once.

function getSessions: () => Promise<SessionWithActivities[]>;

getSessions() returns

TypeDescription
Promise<SessionWithActivities[]>This method returns a Promise which resolves with an array of SessionWithActivities objects.

getSessions() example

import Clerk from '@clerk/clerk-js'; // Initialize Clerk with your Clerk publishable key const clerk = new Clerk(`{{pub_key}}`); await clerk.load(); if (!clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector<HTMLDivElement>( "#app" )!.innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector<HTMLDivElement>("#sign-in")!; clerk.mountSignIn(signInComponent, {}); } else { await clerk.user.getSessions(); }
<script> // Get your publishable key and frontend API URL from the Clerk Dashboard const clerkPublishableKey = `{{pub_key}}`; const frontendApi = 'https://[your-domain].clerk.accounts.dev'; const version = '@latest'; // Set to appropriate version // Creates asynchronous script const script = document.createElement('script'); script.setAttribute('data-clerk-frontend-api', frontendApi); script.setAttribute('data-clerk-publishable-key', clerkPublishableKey); script.async = true; script.src = `${frontendApi}/npm/@clerk/clerk-js${version}/dist/clerk.browser.js`; // Adds listener to initialize ClerkJS after it's loaded script.addEventListener("load", async function () { await window.Clerk.load(); if (!window.Clerk.user) { // Selects for <div id="app"> and adds a <div id="sign-in"> to it document.querySelector("#app").innerHTML = `<div id="sign-in"></div>`; const signInComponent = document.querySelector("#sign-in"); window.Clerk.mountSignIn(signInComponent, {}); } else { await window.Clerk.user.getSessions(); } }); document.body.appendChild(script); </script>

isPrimaryIdentification()

A check whether or not the given resource is the primary identifier for the user.

function isPrimaryIdentification: (ident: EmailAddressResource | PhoneNumberResource | Web3WalletResource) => boolean;

isPrimaryIdentification() params

NameTypeDescription
identEmailAddress | PhoneNumber | Web3WalletThe resource checked against the user to see if it is the primary identifier.

Additional methods

In addition to the methods listed above, the User class also has the following methods:

Time-based one-time password (TOTP)

Password management

Create metadata

Last updated on March 1, 2024

What did you think of this content?

Clerk © 2024