ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β π shadcn/directory/clerk/clerk-docs/reference/javascript/user β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
User object'
description: The User object holds all the information for a user of your application and provides a set of methods to manage their account. Users have a unique authentication identifier which might be their email address, phone number or a username.
sdk: js-frontendThe ClerkJS SDK provides some helper methods on the User object to help retrieve and update user information and authentication status.
A boolean indicating whether the user has enabled backup codes for their account.
createdAtDateThe date when the user was first created.
createOrganizationEnabledbooleanA boolean indicating whether the organization creation permission is enabled for the user. Defaults to false.
createOrganizationsLimitnumberA number indicating the number of organizations that can be created by the user. If the value is 0, then the user can create unlimited organizations. Defaults to null.
deleteSelfEnabledbooleanA boolean indicating whether the user is able to delete their own account.
emailAddressesAn array of all the EmailAddress objects associated with the user. Includes the primary.
enterpriseAccountsAn array of all the EnterpriseAccount objects associated with the user.
externalAccountsAn array of all the ExternalAccount objects associated with the user via OAuth. This includes both verified & unverified external accounts.
externalIdstring | nullThe user's ID as used in your external systems. Must be unique across your instance.
firstNamestring | nullThe user's first name.
fullNamestring | nullThe user's full name.
hasImagebooleanA boolean that indicates whether the user has uploaded an image or one was copied from OAuth. Returns false if Clerk is displaying an avatar for the user.
hasVerifiedEmailAddressbooleanA boolean that indicates whether the user has verified an email address.
hasVerifiedPhoneNumberbooleanA boolean that indicates whether the user has verified a phone number.
idstringThe user's unique identifier.
imageUrlstringHolds the default avatar or user's uploaded profile image. Compatible with Clerk's Image Optimization.
lastSignInAtDate | nullThe date when the user last signed in. null if the user has never signed in.
lastNamestring | nullThe user's last name.
legalAcceptedAtDateThe date when the user accepted the legal documents. null if Require express consent to legal documents is not enabled.
organizationMembershipsA list of OrganizationMemberships representing the list of organizations the user is member with.
passkeysAn array of passkeys associated with the user's account.
passwordEnabledbooleanA boolean indicating whether the user has a password on their account.
phoneNumbersAn array of all the PhoneNumber objects associated with the user. Includes the primary.
primaryEmailAddressInformation about the user's primary email address.
primaryEmailAddressIdstring | nullThe ID for the EmailAddress that the user has set as primary.
primaryPhoneNumberInformation about the user's primary phone number.
primaryPhoneNumberIdstring | nullThe ID for the PhoneNumber that the user has set as primary.
primaryWeb3WalletThe Web3Wallet that the user signed up with.
primaryWeb3WalletIdstring | nullThe ID for the Web3Wallet that the user signed up with.
privateMetadataUserPrivateMetadataMetadata that can be read and set only from the Backend API{{ target: '_blank' }}.
publicMetadataUserPublicMetadataMetadata that can be read from the Frontend API and Backend API{{ target: '_blank' }} and can be set only from the Backend API.
samlAccounts (deprecated)Deprecated in favor of enterpriseAccounts. An array of all the SamlAccount objects associated with the user.
totpEnabledbooleanA boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.
twoFactorEnabledbooleanA boolean indicating whether the user has enabled two-factor authentication.
unsafeMetadataUserUnsafeMetadataMetadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.
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.
updatedAtDateThe date when the user was last updated.
verifiedExternalAccountsAn array of all the ExternalAccount objects associated with the user via OAuth that are verified.
verifiedWeb3WalletsAn array of all the Web3Wallet objects associated with the user that are verified.
unverifiedExternalAccountsAn array of all the ExternalAccount objects associated with the user via OAuth that are not verified.
usernamestring | nullThe user's username. Only supported if username is enabled in the instance settings.
web3WalletsAn array of all the Web3Wallet objects associated with the user. Includes the primary.
</Properties>
createBackupCode()Generates a fresh new set of backup codes for the user. Every time the method is called, it will replace the previously generated backup codes. Returns a BackupCodeResource object.
[!WARNING] Can only be created for the user if the user has another multi-factor authentication method enabled for their account, in the Clerk Dashboard, as backup codes are a fallback for when the user is unable to use their primary MFA method.
function createBackupCode(): Promise<BackupCodeResource>
await clerk.user.createBackupCode()
createEmailAddress()Adds an email address for the user. A new EmailAddress will be created and associated with the user.
[!WARNING] Email must be enabled in your app's settings in the Clerk Dashboard.
function createEmailAddress(params: CreateEmailAddressParams): Promise<EmailAddress>
CreateEmailAddressParamsThe email address to be added to the user. </Properties>
await clerk.user.createEmailAddress({ email: 'test@test.com' })
createExternalAccount()Adds an external account for the user. A new ExternalAccount will be created and associated with the user. This method is useful if you want to allow an already signed-in user to connect their account with an external provider, such as Facebook, GitHub, etc., so that they can sign in with that provider in the future.
[!WARNING] The social provider that you want to connect to must be enabled in your app's settings in the Clerk Dashboard.
function createExternalAccount(params: CreateExternalAccountParams): Promise<ExternalAccount>
CreateExternalAccountParamsThe strategy corresponding to the OAuth provider. For example: 'oauth_facebook', 'oauth_github', etc.
redirectUrl?stringThe full URL or path that the OAuth provider should redirect to, on successful authorization on their part. Typically, this will be a simple /sso-callback route that calls Clerk.handleRedirectCallback or mounts the <AuthenticateWithRedirectCallback /> component. See the custom flow for implementation details.
additionalScopes?string[]Additional scopes for your user to be prompted to approve.
oidcPrompt?stringThe value to pass to the OIDC prompt parameter in the generated OAuth redirect URL.
oidcLoginHint?stringThe value to pass to the OIDC login_hint parameter in the generated OAuth redirect URL.
</Properties>
After calling createExternalAccount, the initial state of the returned ExternalAccount will be unverified. To initiate the connection with the external provider, redirect the user to the externalAccount.verification.externalVerificationRedirectURL contained in the result of createExternalAccount.
Upon return, inspect within the user.externalAccounts the entry that corresponds to the requested strategy:
externalAccount.verification.status will be verified.externalAccount.verification.status will not be verified and the externalAccount.verification.error will contain the error encountered, which you can present to the user. To learn more about the properties available on verification, see the verification reference.The following example demonstrates how to add a Notion account as an external account for the user. When the user selects the "Add Notion as a social connection" button, the user will be redirected to Notion to connect their account. After connecting their account, they will be redirected to the / route of your application, and the status of the connection will be displayed.
<CodeBlockTabs options={["index.html", "main.js"]}>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Clerk + JavaScript App</title>
</head>
<body>
<div id="app"></div>
<p>
Notion verification status:
<span id="notion-status"></span>
</p>
<button id="add-notion">Add Notion as a social connection</button>
<script type="module" src="/main.js"></script>
</body>
</html>
import { Clerk } from '@clerk/clerk-js'
// Initialize Clerk with your Clerk Publishable Key
const pubKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY
const clerk = new Clerk(pubKey)
await clerk.load()
if (clerk.isSignedIn) {
// Find the external account for the provider
const externalAccount = clerk.user.externalAccounts.find((p) => p.provider === 'notion')
// If the external account exists, display its status
document.getElementById('notion-status').innerHTML = externalAccount.verification.status
// When the button is clicked, initiate the connection with the provider
document.getElementById('add-notion').addEventListener('click', async () => {
clerk.user
.createExternalAccount({ strategy: 'oauth_notion', redirect_url: '/' })
.then((externalAccount) => {
window.location.href = externalAccount.verification.externalVerificationRedirectURL
})
.catch((error) => {
console.log('An error occurred:', error.errors)
})
})
} else {
document.getElementById('app').innerHTML = `
<div id="sign-in"></div>
`
const signInDiv = document.getElementById('sign-in')
clerk.mountSignIn(signInDiv)
}
</CodeBlockTabs>
createPasskey()Creates a passkey for the signed-in user. Returns a PasskeyResource object.
[!NOTE] When creating a passkey for a user in a multi-domain Clerk app,
createPasskey()must be called from the primary domain.
function createPasskey(): Promise<PasskeyResource>
For an example on how to use createPasskey(), see the custom flow guide on passkeys.
createPhoneNumber()Adds a phone number for the user. A new PhoneNumber will be created and associated with the user.
[!WARNING] Phone must be enabled in your app's settings in the Clerk Dashboard.
function createPhoneNumber(params: CreatePhoneNumberParams): Promise<PhoneNumberResource>
CreatePhoneNumberParamsThe phone number to be added to the user. Must be in E.164 format. </Properties>
await clerk.user.createPhoneNumber({ phoneNumber: '1234567890' })
createTOTP()Generates a TOTP secret for a user that can be used to register the application on the user's authenticator app of choice. If this method is called again (while still unverified), it replaces the previously generated secret. Returns a TOTPResource object.
[!WARNING] The Authenticator application multi-factor strategy must be enabled in your app's settings in the Clerk Dashboard. See the Multi-factor authentication section to learn more.
function createTOTP(): Promise<TOTPResource>
await clerk.user.createTOTP()
delete()Deletes the current user.
function delete(): Promise<void>
await clerk.user.delete()
disableTOTP()Disables TOTP by deleting the user's TOTP secret. Returns a DeletedObjectResource object.
[!WARNING] The Authenticator application multi-factor strategy must be enabled in your app's settings in the Clerk Dashboard. See the Multi-factor authentication section to learn more.
function disableTOTP(): Promise<DeletedObjectResource>
await clerk.user.disableTOTP()
getOrganizationInvitations()Retrieves a list of organization invitations for the user. Returns a ClerkPaginatedResponse of UserOrganizationInvitation objects.
function getOrganizationInvitations(
params?: GetUserOrganizationInvitationsParams,
): Promise<ClerkPaginatedResponse<UserOrganizationInvitation>>
GetUserOrganizationInvitationsParamsA number that can be used to skip the first n-1 pages. For example, if initialPage is set to 10, it is will skip the first 9 pages and will fetch the 10th page.
pageSize?numberA number that indicates the maximum number of results that should be returned for a specific page.
status?'pending' | 'accepted' | 'revoked'The status an invitation can have. </Properties>
await clerk.user.getOrganizationInvitations()
getOrganizationMemberships()Retrieves a list of organization memberships for the user. Returns a ClerkPaginatedResponse of OrganizationMembershipResource objects.
function getOrganizationMemberships(
params?: GetUserOrganizationMembershipParams,
): Promise<ClerkPaginatedResponse<OrganizationMembershipResource>>
GetUserOrganizationMembershipParamsA number that can be used to skip the first n-1 pages. For example, if initialPage is set to 10, it is will skip the first 9 pages and will fetch the 10th page.
pageSize?numberA number that indicates the maximum number of results that should be returned for a specific page. </Properties>
await clerk.user.getOrganizationMemberships()
getOrganizationSuggestions()Retrieves a list of organization suggestions for the user. Returns a ClerkPaginatedResponse of OrganizationSuggestion objects.
function getOrganizationSuggestions(
params?: GetUserOrganizationSuggestionsParams,
): Promise<ClerkPaginatedResponse<OrganizationSuggestion>>
GetUserOrganizationSuggestionsParamsA number that can be used to skip the first n-1 pages. For example, if initialPage is set to 10, it is will skip the first 9 pages and will fetch the 10th page.
pageSize?numberA number that indicates the maximum number of results that should be returned for a specific page.
status?'pending' | 'accepted' | ['pending' | 'accepted']The status an invitation can have. </Properties>
await clerk.user.getOrganizationSuggestions()
getSessions()Retrieves all active sessions for this user. This method uses a cache so a network request will only be triggered only once. Returns an array of SessionWithActivities objects.
function getSessions(): Promise<SessionWithActivities[]>
await clerk.user.getSessions()
isPrimaryIdentification()A check whether or not the given resource is the primary identifier for the user.
function isPrimaryIdentification(
ident: EmailAddressResource | PhoneNumberResource | Web3WalletResource,
): boolean
The resource checked against the user to see if it is the primary identifier. </Properties>
await clerk.user.isPrimaryIdentification(clerk.user.emailAddresses[0])
reload()Reloads the user's data from Clerk's API. Useful for when you want to refresh the user's data after performing some form of mutation.
<Include src="_partials/user-reload" />function reload(p?: ClerkResourceReloadParams): Promise<this>
ClerkResourceReloadParamsA nonce to use for rotating the user's token. Used in native application OAuth flows to allow the native client to update its JWT once despite changes in its rotating token. </Properties>
await clerk.user.reload()
removePassword()Removes the user's password.
function removePassword(params: RemoveUserPasswordParams): Promise<User>
RemoveUserPasswordParamsThe user's current password. </Properties>
await clerk.user.removePassword({ currentPassword: 'current-password' })
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>
SetProfileImageParamsThe file to set as the user's profile image, or null to remove the current image.
</Properties>
ImageResourceThe unique identifier of the image.
namestring | nullThe name of the image.
publicUrlstring | nullThe publicly accessible url for the image. </Properties>
await clerk.user.setProfileImage({ file: profileImage })
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 First and last name setting. It can be found on the User & authentication page in the Clerk Dashboard.
function update(params: UpdateUserParams): Promise<User>
UpdateUserParamsAll props below are optional.
<Properties> - `username` - `string`The user's username. Only supported if username is enabled in the instance settings.
firstNamestringThe user's first name.
lastNamestringThe user's last name.
primaryEmailAddressIdstringThe ID for the EmailAddress that the user has set as primary.
primaryPhoneNumberIdstringThe ID for the PhoneNumber that the user has set as primary.
primaryWeb3WalletIdstringThe ID for the Web3Wallet that the user signed up with.
unsafeMetadataUserUnsafeMetadataMetadata 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. Updating this value overrides the previous value; it does not merge. To perform a merge, you can pass something like { β¦user.unsafeMetadata, β¦newData } to this parameter.
</Properties>
await clerk.user.update({ firstName: 'Test' })
updatePassword()Updates the user's password. Passwords must be at least 8 characters long.
function updatePassword(params: UpdateUserPasswordParams): Promise<User>
UpdateUserPasswordParamsThe user's new password.
currentPassword?stringThe user's current password.
signOutOfOtherSessions?boolean | undefinedIf set to true, all sessions will be signed out.
</Properties>
await clerk.user.updatePassword({
currentPassword: 'current-password',
newPassword: 'new-password',
})
verifyTOTP()Verifies a TOTP secret after a user has created it. The user must provide a code from their authenticator app that has been generated using the previously created secret. This way, correct set up and ownership of the authenticator app can be validated. Returns a TOTPResource object.
[!WARNING] The Authenticator application multi-factor strategy must be enabled in your app's settings in the Clerk Dashboard. See the Multi-factor authentication section to learn more.
function verifyTOTP(params: VerifyTOTPParams): Promise<TOTPResource>
VerifyTOTPParamsA 6 digit TOTP generated from the user's authenticator app. </Properties>
await clerk.user.verifyTOTP({ code: '123456' })
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ