User
object
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 social 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, but public metadata can also be accessed from the Frontend API.
The ClerkJS SDK provides some helper methods on the User
object to help retrieve and update user information and authentication status.
Properties
- Name
backupCodeEnabled
- Type
boolean
- Description
A boolean indicating whether the user has enabled backup codes for their account.
- Name
createdAt
- Type
Date
- Description
The date when the user was first created.
- Name
createOrganizationEnabled
- Type
boolean
- Description
A boolean indicating whether the organization creation permission is enabled for the user. Defaults to
false
.
- Name
createOrganizationsLimit
- Type
number
- Description
A 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 tonull
.
- Name
deleteSelfEnabled
- Type
boolean
- Description
A boolean indicating whether the user is able to delete their own account.
- Name
emailAddresses
- Type
[EmailAddress][email-ref][]
- Description
An array of all the
EmailAddress
objects associated with the user. Includes the primary.
- Name
enterpriseAccounts
- Type
EnterpriseAccount[]
- Description
An array of all the
EnterpriseAccount
objects associated with the user.
- Name
externalAccounts
- Type
[ExternalAccount][exacc-ref][]
- Description
An array of all the
ExternalAccount
objects associated with the user via OAuth. This includes both verified & unverified external accounts.
- Name
externalId
- Type
string | null
- Description
The user's ID as used in your external systems. Must be unique across your instance.
- Name
firstName
- Type
string | null
- Description
The user's first name.
- Name
fullName
- Type
string | null
- Description
The user's full name.
- Name
hasImage
- Type
boolean
- Description
A 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.
- Name
hasVerifiedEmailAddress
- Type
boolean
- Description
A boolean that indicates whether the user has verified an email address.
- Name
hasVerifiedPhoneNumber
- Type
boolean
- Description
A boolean that indicates whether the user has verified a phone number.
- Name
id
- Type
string
- Description
The user's unique identifier.
- Name
imageUrl
- Type
string
- Description
Holds the default avatar or user's uploaded profile image. Compatible with Clerk's Image Optimization.
- Name
lastSignInAt
- Type
Date | null
- Description
The date when the user last signed in.
null
if the user has never signed in.
- Name
lastName
- Type
string | null
- Description
The user's last name.
- Name
legalAcceptedAt
- Type
Date
- Description
The date when the user accepted the legal documents.
null
if Require express consent to legal documents is not enabled.
- Name
organizationMemberships
- Type
OrganizationMembership[]
- Description
A list of
OrganizationMembership
s representing the list of organizations the user is member with.
- Name
passkeys
- Type
PasskeyResource[] | null
- Description
An array of passkeys associated with the user's account.
- Name
passwordEnabled
- Type
boolean
- Description
A boolean indicating whether the user has a password on their account.
- Name
phoneNumbers
- Type
[PhoneNumber][phone-ref][]
- Description
An array of all the
PhoneNumber
objects associated with the user. Includes the primary.
- Name
primaryEmailAddress
- Type
[EmailAddress][email-ref] | null
- Description
Information about the user's primary email address.
- Name
primaryEmailAddressId
- Type
string | null
- Description
The ID for the
EmailAddress
that the user has set as primary.
- Name
primaryPhoneNumber
- Type
[PhoneNumber][phone-ref] | null
- Description
Information about the user's primary phone number.
- Name
primaryPhoneNumberId
- Type
string | null
- Description
The ID for the
PhoneNumber
that the user has set as primary.
- Name
primaryWeb3Wallet
- Type
[Web3Wallet][web3-ref] | null
- Description
The
Web3Wallet
that the user signed up with.
- Name
primaryWeb3WalletId
- Type
string | null
- Description
The ID for the [
Web3Wallet
][web3-ref] that the user signed up with.
- Name
privateMetadata
- Type
UserPrivateMetadata
- Description
Metadata that can be read and set only from the Backend API.
- Name
publicMetadata
- Type
UserPublicMetadata
- Description
Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.
- Name
samlAccounts
(deprecated)- Type
SamlAccount[]
- Description
Deprecated in favor of
enterpriseAccounts
. An array of all theSamlAccount
objects associated with the user.
- Name
totpEnabled
- Type
boolean
- Description
A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.
- Name
twoFactorEnabled
- Type
boolean
- Description
A boolean indicating whether the user has enabled two-factor authentication.
- Name
unsafeMetadata
- Type
UserUnsafeMetadata
- Description
Metadata 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 theSignUp
object. The value of that field will be automatically copied to the user's unsafe metadata once the sign up is complete.
- Name
updatedAt
- Type
Date
- Description
The date when the user was last updated.
- Name
verifiedExternalAccounts
- Type
[ExternalAccount][exacc-ref][]
- Description
An array of all the
ExternalAccount
objects associated with the user via OAuth that are verified.
- Name
verifiedWeb3Wallets
- Type
[Web3Wallet][web3-ref][]
- Description
An array of all the
Web3Wallet
objects associated with the user that are verified.
- Name
unverifiedExternalAccounts
- Type
[ExternalAccount][exacc-ref][]
- Description
An array of all the
ExternalAccount
objects associated with the user via OAuth that are not verified.
- Name
username
- Type
string | null
- Description
The user's username.
- Name
web3Wallets
- Type
[Web3Wallet][web3-ref][]
- Description
An array of all the
Web3Wallet
objects associated with the user. Includes the primary.
Methods
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.
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.
function createEmailAddress(params: CreateEmailAddressParams): Promise<EmailAddress>
- Name
email
- Type
string
- Description
The value of the email address
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.
function createExternalAccount(params: CreateExternalAccountParams): Promise<ExternalAccount>
- Name
strategy
- Type
OAuthStrategy
- Description
The strategy corresponding to the OAuth provider. For example:
'oauth_facebook'
,'oauth_github'
, etc.
- Name
redirectUrl?
- Type
string
- Description
The 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 callsClerk.handleRedirectCallback
or mounts the<AuthenticateWithRedirectCallback />
component. See the custom flow for implementation details.
- Name
additionalScopes?
- Type
string[]
- Description
Additional scopes for your user to be prompted to approve.
- Name
oidcPrompt?
- Type
string
- Description
The value to pass to the OIDC
prompt
parameter in the generated OAuth redirect URL.
- Name
oidcLoginHint?
- Type
string
- Description
The value to pass to the OIDC
login_hint
parameter in the generated OAuth redirect URL.
Example
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:
- If the connection succeeded, then
externalAccount.verification.status
will beverified
. - If the connection failed, then the
externalAccount.verification.status
will not beverified
and theexternalAccount.verification.error
will contain the error encountered, which you can present to the user. To learn more about the properties available onverification
, see theverification
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.
<!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.user) {
// 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)
}
createPasskey()
Creates a passkey for the signed-in user. Returns a PasskeyResource
object.
function createPasskey(): Promise<PasskeyResource>
Example
For an example on how to use createPasskey()
, see the custom flow guide on passkeys.
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.
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 DeletedObject
object.
function disableTOTP(): Promise<DeletedObject>
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>>
- Name
initialPage?
- Type
number
- Description
A 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.
- Name
pageSize?
- Type
number
- Description
A number that indicates the maximum number of results that should be returned for a specific page.
- Name
status?
- Type
'pending' | 'accepted' | 'revoked'
- Description
The status an invitation can have.
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>>
- Name
initialPage?
- Type
number
- Description
A 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.
- Name
pageSize?
- Type
number
- Description
A number that indicates the maximum number of results that should be returned for a specific page.
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>>
- Name
initialPage?
- Type
number
- Description
A 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.
- Name
pageSize?
- Type
number
- Description
A number that indicates the maximum number of results that should be returned for a specific page.
- Name
status?
- Type
'pending' | 'accepted' | ['pending' | 'accepted']
- Description
The status an invitation can have.
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
- Name
ident
- Type
[EmailAddress][email-ref] | [PhoneNumber][phone-ref] | [Web3Wallet][web3-ref]
- Description
The resource checked against the user to see if it is the primary identifier.
await clerk.user.isPrimaryIdentification(clerk.user.emailAddresses[0])
removePassword()
Removes the user's password.
function removePassword(params: RemoveUserPasswordParams): Promise<User>
- Name
currentPassword
- Type
string
- Description
The user's current password.
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>
- Name
file
- Type
Blob | File | string | null
- Description
The file to set as the user's profile image, or
null
to remove the current image.
ImageResource
- Name
id?
- Type
string
- Description
The unique identifier of the image.
- Name
name
- Type
string | null
- Description
The name of the image.
- Name
publicUrl
- Type
string | null
- Description
The publicly accessible url for the image.
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 Name setting. It can be found on the Email, phone, username > Personal information section in the Clerk Dashboard.
function update(params: UpdateUserParams): Promise<User>
UpdateUserParams
All props below are optional.
- Name
username
- Type
string
- Description
The user's username.
- Name
firstName
- Type
string
- Description
The user's first name.
- Name
lastName
- Type
string
- Description
The user's last name.
- Name
primaryEmailAddressId
- Type
string
- Description
The ID for the [
EmailAddress
][email-ref] that the user has set as primary.
- Name
primaryPhoneNumberId
- Type
string
- Description
The ID for the [
PhoneNumber
][phone-ref] that the user has set as primary.
- Name
primaryWeb3WalletId
- Type
string
- Description
The ID for the [
Web3Wallet
][web3-ref] that the user signed up with.
- Name
unsafeMetadata
- Type
UserUnsafeMetadata
- Description
Metadata 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.
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>
- Name
newPassword
- Type
string
- Description
The user's new password.
- Name
currentPassword?
- Type
string
- Description
The user's current password.
- Name
signOutOfOtherSessions?
- Type
boolean | undefined
- Description
If set to
true
, all sessions will be signed out.
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.
function verifyTOTP(params: VerifyTOTPParams): Promise<TOTPResource>
- Name
code
- Type
string
- Description
A 6 digit TOTP generated from the user's authenticator app.
await clerk.user.verifyTOTP({ code: '123456' })
Feedback
Last updated on