Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev
Check out a preview of our new docs.

Clerk

The Clerk object is the core of the ClerkJS SDK.

Overview

The Clerk object is a singleton which can act as the entry point for gaining access to other Clerk resources, like the active Client, Session and User objects. It also includes helper methods for mounting Clerk Components to your pages.

The Clerk object is always available via window.Clerk.

Attributes

NameTypeDescription
clientClient

The Client object for the current window.

sessionsession ​ | null | undefined

The currently active Session, which is guaranteed to be one of the sessions in Client.sessions. If there is no active session, this field will be null. If the session is loading, this field will be undefined.

userUser | null | undefined

A shortcut to Session.user which holds the currently active User object. If the session is null or undefined, the user field will match.

versionstring

The ClerkJS SDK version.

Methods

addListener(listener)

addListener(listener: (resources: Resources) => void) => UnsubscribeCallback

Resources is an interface with the following definition. To import our types, please add @clerk/types:

interface Resources {
client: ClientResource;
session?: ActiveSessionResource | null;
user?: UserResource | null;
}

Please note that the session and user object have a special relationship that the type definition alone does not capture:

  • When there is an active session, user === session.user.When there is no active session, userand sessionwill both be null.
  • When a session is loading, userand sessionwill be undefined.

Parameters

NameTypeDescription
listener(resources: Resources) => void

A function to be called when the Client object changes.

Returns

TypeDescription
() => void

This method returns a function that can be used to clean up the registered listener.

authenticateWithMetamask(params)

authenticateWithMetamask(params: AuthenticateWithMetamaskParams) => void

Starts an authentication flow that uses the Metamask browser extension to authenticate the user using their public wallet address.

Parameters

TypeDescription
AuthenticateWithMetamaskParams​

​​These props allow you to define the URL where the user should be redirected to on successful authentication

Returns

The method has no return value.

buildSignInUrl(opts)

buildSignInUrl(opts?: RedirectOptions) => string

Returns the configured url where <SignIn /> is mounted or a custom sign-in page is rendered.

buildSignUpUrl(opts)

buildSignUpUrl(opts?: RedirectOptions) => string

Returns the configured url where <SignUp /> is mounted or a custom sign-up page is rendered.

buildUserProfileUrl()

buildUserProfileUrl() => string

Returns the url where <UserProfile /> is mounted or a custom user-profile page is rendered.

buildCreateOrganizationUrl()

buildCreateOrganizationUrl() => string

Returns the configured url where <CreateOrganization /> is mounted or a custom create-organization page is rendered.

buildOrganizationProfileUrl()

buildOrganizationProfileUrl() => string

Returns the configured url where <OrganizationProfile /> is mounted or a custom organization-profile page is rendered.

buildUrlWithAuth(to)

buildUrlWithAuth(to: string) => string

Decorates the provided url with the auth token for development instances.

closeSignIn()

closeSignIn() => void

Closes the <SignIn/> modal.

Parameters

This method accepts no parameters.

Returns

The method has no return value.

closeSignUp()

closeSignUp() => void

Closes the <SignUp/> modal.

Parameters

This method accepts no parameters.

Returns

The method has no return value.

handleRedirectCallback(params: HandleMagicLinkVerificationParams) => Promise<unknown>

Completes a magic link verification flow once we've reached the magic link results URL.

When users click on magic links they get redirected to the URL that was provided during magic link verification flow initialization. The URL will contain a couple of important query parameters added by Clerk. These are called __clerk_status and __clerk_created_session.

The __clerk_status query parameter is the outcome of the verification and can take three values: verified, failed or expired.

The __clerk_created_session query parameter will hold the ID of the new session, if one was created as a result of the verification. Since the magic link can be opened at any device and not the one that originated the verification, the new session ID might not be available under Client.sessions.

Magic link flows can be completed on the same device that they were initiated or on a completely different browser. For example, a user might start the magic link flow on their desktop browser, but click on the magic link from their mobile phone.

The handleMagicLinkVerification() method takes care of finalizing the magic link flow, depending on the verification outcome.

Upon successful verification, the method will figure out if the sign in or sign up attempt was completed and redirect the user accordingly. As such, it accepts different parameters for the URL it should redirect when sign in/up is completed and the URL which it should redirect when the sign in/up attempt is still pending. Both parameters are optional, but you can provide them to the method up front. The final redirect will depend on the sign in/up attempt's status.

Additionally, the handleMagicLinkVerification() method allows you to execute a callback if the successful verification happened on another device.

In case the magic link verification wasn't successful, the handleMagicLinkVerification() method will throw a MagicLinkError. You can check the error's code property to see if the magic link expired, or the verification simply failed.

Take a look at the function parameters description below for more usage details.

Parameters

NameTypeDescription
paramsHandleMagicLinkVerificationParams

These props allow you to define the URLs where the user should be redirected to on successful verification and:

  • completed sign in or sign up attempt.
  • pending sign in or sign up attempt.

If the magic link is successfully verified on another device, there's a callback function parameter that allows custom code execution.

Returns

TypeDescription
MagicLinkError

MagicLinkError
This method will throw a MagicLinkError if the magic link verification failed or the link expired. Check the error's code property for details.

handleRedirectCallback(params)

handleRedirectCallback(params: HandleOAuthCallbackParams) => Promise<void>

Completes a custom OAuth flow started by calling either SignIn.authenticateWithRedirect(params) or SignUp.authenticateWithRedirect(params)

Parameters

NameTypeDescription
paramsHandleOAuthCallbackParams

Additional props that define where the user will be redirected to at the end of a successful OAuth flow.

isReady()

isReady() => boolean

Returns true when the ClerkJS library has fully loaded and the Clerk object is ready for use, false otherwise.

Parameters

This method accepts no parameters.

Returns

TypeDescription
boolean

This method will return true when the Clerk object is ready, false otherwise.

load(options?)

load(options?: ComponentOptions) => Promise<void>

Initializes the Clerk object and loads all necessary environment configuration and Instance settings from the Frontend API.

It is absolutely necessary to call this method before using the Clerk object in your code. Refer to the ClerkJS installation guide for more details.

Parameters

NameTypeDescription
optionsComponentOptions

Configuration and options for initializing the Clerk object and Clerk Components.

Returns

TypeDescription
boolean

This method will return true when the Clerk object is ready, false otherwise.

mountSignIn(node, nodeProps?)

mountSignIn(node: HTMLDivElement, nodeProps?: SignInProps) => void

Renders a <SignIn/> component inside the provided HTML element, allowing to pass any props that configure the component.

Parameters

NameTypeDescription
nodeHTMLDivElement

An HTML <div/> element which will render the <SignIn/> component.

nodeProps?SignInProps

Additional props that will be passed to the <SignIn/> component.

Returns

TypeDescription
boolean

This method will return true when the Clerk object is ready, false otherwise.

mountSignUp(node, nodeProps?)

mountSignUp(node: HTMLDivElement, nodeProps?: SignUpProps) => void

Renders a <SignUp/> component inside the provided HTML element, allowing to pass any props that configure the component.

Parameters

NameTypeDescription
nodeHTMLDivElement

An HTML <div/> element which will render the <SignUp/> component.

nodeProps?SignUpProps

Additional props that will be passed to the <SignUp/> component.

Returns

This method has no return value.

mountUserButton(node, nodeProps?)

mountUserButton(node: HTMLDivElement, nodeProps?: UserButtonProps) => void

Renders a <UserButton/> component for the active user inside the provided HTML element, allowing to pass any props that configure the component.

Parameters

NameTypeDescription
nodeHTMLDivElement

An HTML <div/> element which will render the <UserButton/> component.

nodeProps?UserButtonProps

Additional props that will be passed to the <UserButton/> component.

Returns

This method has no return value.

mountUserProfile(node, nodeProps?)

mountUserProfile(node: HtmlDivElement, nodeProps?: UserProfileProps) => void

Renders a <UserProfile/> component for the active user inside the provided HTML element, allowing to pass any props that configure the component.

Parameters

NameTypeDescription
nodeHTMLElement

The element that the UserProfile should be mounted in.

nodeProps?UserProfileProps

Additional props that will be passed to the <UserProfile/> component.

Returns

This method has no return value.

navigate(to: string) => Promise<unknown>

Helper method which will use the custom push navigation function of your application to navigate to the provided URL or relative path. See the relevant section on routing for more information on navigation.

Parameters

NameTypeDescription
propsSignInProps

Configuration properties that will be passed to the <SignIn/> component.

Returns

This method has no return value.

openSignIn(props)

openSignIn(props: SignInProps) => void

Opens the <SignIn/> component as a modal.

Parameters

NameTypeDescription
propsSignInProps

Configuration properties that will be passed to the <SignIn/> component.

Returns

This method has no return value.

openSignUp(props)

openSignUp(props: SignUpProps) => void

Opens the <SignUp/> component as a modal.

Parameters

NameTypeDescription
propsSignUpProps

Configuration properties that will be passed to the <SignUp/> component.

Returns

This method has no return value.

redirectToCreateOrganization()

redirectToCreateOrganization() => void

Redirects to the configured URL where <CreateOrganization /> is mounted.

redirectToOrganizationProfile()

redirectToOrganizationProfile() => void

Redirects to the configured URL where <OrganizationProfile /> is mounted.

redirectToSignIn(props)

redirectToSignIn(props: RedirectToSignInProps) => Promise<unknown>

Redirects to the sign-in URL, as configured in your Instance settings. This method uses the Clerk.navigate method under the hood.

Parameters

NameTypeDescription
afterSignInUrlstring

Full URL or path to navigate after successful sign-in.

afterSignUpUrlstring

Full URL or path to navigate after successful sign-up. Sets the afterSignUpUrl if the "Sign up" link is clicked.

redirectUrlstring

Full URL or path to navigate after successful sign-in, or sign-up. The same as setting afterSignInUrl and afterSignUpUrl to the same value.

Returns

TypeDescription
Promise<unknown>

This method returns a Promise which can resolve to any value.

redirectToSignUp(props)

redirectToSignUp(props: RedirectToSignUpProps) => Promise<unknown>

Redirects to the sign-up URL, as configured in your Instance settings. This method uses the Clerk.navigate method under the hood.

Parameters

NameTypeDescription
afterSignInUrlstring

Full URL or path to navigate after successful sign-in.

afterSignUpUrlstring

Full URL or path to navigate after successful sign up. Sets the afterSignUpUrl if the "Sign up" link is clicked.

redirectUrlstring

Full URL or path to navigate after successful sign-in, or sign-up. The same as setting afterSignInUrl and afterSignUpUrl to the same value.

Returns

TypeDescription
Promise<unknown>

This method returns a Promise which can resolve to any value.

redirectToUserProfile()

redirectToUserProfile() => Promise<unknown>

Redirects to the user profile management URL, as configured in your Instance settings. This method uses the Clerk.navigate method under the hood.

Parameters

This method accepts no parameters.

Returns

TypeDescription
Promise<unknown>

This method returns a Promise which can resolve to any value.

redirectWithAuth(to)

redirectWithAuth(to: string) => Promise<unknown>

Redirects to the provided url after decorating it with the auth token for development instances.

setSession(session, beforeEmit?)

setSession(session: SessionResource | string | null, beforeEmit?: (session: SessionResource | null) => any) => Promise<void>

Set the current session on this client to the provided session. The provided session can be either a complete Session object or simply its unique identifier.

Passing null as the session will result in the current session to be removed from the client.

If an active session already exists, it will be replaced with the new one. The change happens in three steps:

  1. The current Session object is set to undefined, which causes the control components to stop rendering their children as though Clerk is still initializing.
  2. The beforeEmit callback is executed. If a Promise is returned, Clerk waits for the Promise to resolve.
  3. The current Session is set to the passed session. This causes the control components to render their children again.

Parameters

NameTypeDescription
sessionSessionResource | string | null

A Session object or Session ID string to be set as the current session, or null to simply remove the active session, without setting a new one.

beforeEmit?(session: SessionResource | null) => Promise<any> | void

Callback that will trigger when the current session is set to undefined, before finally being set to the passed session. Usually used for navigation.

Returns

TypeDescription
Promise<void>

This method returns a Promise which doesn't resolve to any value. The Promise will resolve after the passed session is set.

signOut(callback?)

signOut(callback?: SignOutCallback) => Promise<void>

Signs out the active user from all sessions in a multi-session application, or simply the current session in a single-session context. The current client will be deleted.

Parameters

NameTypeDescription
callback?SignOutCallback

A callback function that will be called after successful sign out.

Returns

TypeDescription
Promise<void>

This method returns a Promise which doesn't resolve to any value.

unmountSignIn(node)

unmountSignIn(node: HTMLDivElement) => void

Unmounts the <SignIn/> component from the specified HTML element.

Parameters

NameTypeDescription
nodeHTMLDivElement

The element that the <SignIn/> component will be unmounted from.

Returns

This method has no return value.

unmountSignUp(node)

unmountSignUp(node: HTMLDivElement) => void

Unmounts the <SignUp/> component from the specified HTML element.

Parameters

NameTypeDescription
nodeHTMLDivElement

The element that the <SignUp/> component will be unmounted from.

Returns

This method has no return value.

unmountUserButton(node)

unmountUserButton(node: HTMLDivElement) => void

Unmounts the <UserButton/> component from the specified HTML element.

Parameters

NameTypeDescription
nodeHTMLDivElement

The element that the <UserButton/> component will be unmounted from.

Returns

This method has no return value.

unmountUserProfile(node)

unmountUserProfile(node: HTMLDivElement) => void

Unmounts the <UserProfile/> component from the specified HTML element.

Parameters

NameTypeDescription
nodeHTMLDivElement

The element that the <UserProfile/> component will be unmounted from.

Returns

This method has no return value.

Interfaces

ComponentOptions

NameTypeDescription
selectInitialSession?(client: ClientResource) => SessionResource | undefined

This function can be used to set the initial session in multi-session applications.

navigate?(to: string) => Promise<unknown> | unknown

Provide an implementation for the Clerk.navigate method.

AuthenticateWithMetamaskParams

NameTypeDescription
redirectUrl?string

Full URL or path to navigate after successful sign in or sign up.

NameTypeDescription
redirectUrl?string

Full URL or path to navigate after successful magic link verification on the same device, but a sign in or sign up attempt that cannot complete yet. For example, let's say a user has enabled two-factor authentication (2FA). In the sign in flow, the magic link verification may be successfully verified but user needs to complete 2FA before they can log in. Use this parameter to redirect to your 2FA route.

redirectUrlComplete?string

Full URL or path to navigate after successful magic link verification on the same device and the sign in or sign up attempt has completed. As an example, user tries to sign in via a magic link and they're successfully logged in. Use this parameter to decide where the user will be redirected to.

onVerifiedOnOtherDevice?Function

Use this callback function to run any custom code on a successful magic link verification on a device different than the one which originated the magic link verification flow. This function provides an opportunity to handle the case where a magic link is opened from another device.

HandleOAuthCallbackParams

NameTypeDescription
afterSignInUrl?string

Full URL or path to navigate after successful sign in.

afterSignUpUrl?string

Full URL or path to navigate after successful sign up.

redirectUrl?Function

Full URL or path to navigate after successful sign in or sign up. The same as setting afterSignInUrl and afterSignUpUrl to the same value.

secondFactorUrl?string

Full URL or path to navigate during sign in, if 2FA is enabled.

SignInProps

NameTypeDescription
routing?RoutingStrategy

The routing strategy for your pages. Supported values are:

  • path: Path based routing.
  • hash(default): Hash based routing.
  • virtual: Virtual based routing.
path?string

The path where the component is mounted when path-based routing is used.

-e.g. /sign-in. This prop is ignored in hash and virtual based routing.

afterSignIn?string

The full URL or path to navigate after a successful sign in.

signInURL?string

Full URL or path to the sign up page. Use this property to provide the target of the "Sign In" link that's rendered.

SignUpProps

NameTypeDescription
routing?string

The routing strategy for your pages. Supported values are:

  • path: Path based routing.
  • hash(default): Hash based routing.
  • virtual: Virtual based routing.
path?string

The path where the component is mounted when path-based routing is used.

-e.g. /sign-up. This prop is ignored in hash and virtual based routing.

afterSignIn?string

The full URL or path to navigate after a successful sign up.

signUpURL?string

Full URL or path to the sign up page. Use this property to provide the target of the "Sign Up" link that's rendered.

UserButtonProps

NameTypeDescription
afterSignOutAll?string

Full URL or relative path to navigate after sign out is complete and there are no active sessions on this client.

afterSignOutOne?string

Full URL or relative path to navigate after sign out is complete.

afterSwitchSession?string

Full URL or relative path to navigate on the "Add another account" action. This property is used only for multi-session applications.

signInURL?string

Full URL or relative path to navigate on the "Add another account" action. This property is used only for multi-session applications.

userProfileURL?string

Full URL or relative path of the user account management interface.

UserProfileProps

NameTypeDescription
routing?string

The routing strategy for your pages. Supported values are:

  • path: Path based routing.
  • hash(default): Hash based routing.
  • virtual: Virtual based routing.
path?string

The path where the component is mounted when path-based routing is used.

-e.g. /user-profile. This prop is ignored in hash and virtual based routing.

hideNavigation?boolean

Hides the default navigation bar. Can be used when a custom navigation bar is built.

only?string

Renders only a specific page of the UserProfile component. Supported values are:

  • account: User account page.
  • security: User security page.

Types

Custom error for magic links. Raised when the magic link verification doesn't succeed, either because the link has expired or a general failure. The error's code property will indicate the outcome, its values being:

  • MagicLinkErrorCode.Expired
  • MagicLinkErrorCode.Failed

SignOutCallback

() => void | Promise<any>

NameDescription
() => void

A Function which doesn't return anything.

Promise<any>

A Promise which can resolve to any value.

Was this helpful?

Clerk © 2023