Docs

Session

The Session object is an abstraction over an HTTP session. It models the period of information exchange between a user and the server.

The Session object includes methods for recording session activity and ending the session client-side. For security reasons, sessions can also expire server-side.

As soon as a User signs in, Clerk creates a Session for the current Client. Clients can have more than one sessions at any point in time, but only one of those sessions will be active.

In certain scenarios, a session might be replaced by another one. This is often the case with multi-session applications.

All sessions that are expired, removed, replaced, ended or abandoned are not considered valid.

Note

For more information regarding the different session states, see the guide on session management.

  • Name
    id
    Type
    string
    Description

    A unique identifier for the session.

  • Name
    user
    Type
    User
    Description

    The user associated with the session.

  • Name
    publicUserData
    Type
    PublicUserData
    Description

    Public information about the user that this session belongs to.

  • Name
    status
    Type
    SessionStatus
    Description

    The current state of the session.

  • Name
    lastActiveAt
    Type
    Date
    Description

    The time the session was last active on the Client.

  • Name
    abandonAt
    Type
    Date
    Description

    The time when the session was abandoned by the user.

  • Name
    expireAt
    Type
    Date
    Description

    The time the session expires and will cease to be active.

  • Name
    updatedAt
    Type
    Date
    Description

    The last time the session recorded activity of any kind.

  • Name
    createdAt
    Type
    Date
    Description

    The time the session was created.

  • Name
    lastActiveToken
    Type
    TokenResource | null
    Description

    The last active token for the session

  • Name
    lastActiveOrganizationId
    Type
    string | null
    Description

    The last active organization identifier

  • Name
    factorVerificationAge
    Type
    [number, number] | null
    Description

    An array where each item represents the number of minutes since the last verification of a first or second factor: [firstFactorAge, secondFactorAge].

  • Name
    actor
    Type
    ActJWTClaim | null
    Description

    The JWT actor for the session

Methods

end()

Marks the session as ended. The session will no longer be active for this Client and its status will become ended.

function end(): Promise<Session>

remove()

Marks the session as removed. The session will no longer be active for this Client and its status will become removed.

function remove(): Promise<Session>

touch()

Touches the session, signifying some kind of user activity. Use this method to record any updates to user activity.

function touch(): Promise<Session>

getToken()

Retrieves the user's session token for the default Clerk token or the given template.

This method uses a cache so a network request will only be made if the token in memory has expired. The TTL for a Clerk token is one minute.

Tokens can only be generated if the user is signed in.

function getToken(options?: GetTokenOptions): Promise<string | null>
  • Name
    leewayInSeconds
    Type
    number
    Description

    The number of seconds to allow the token to be cached for.

  • Name
    template?
    Type
    string
    Description

    The name of the JWT template from the Clerk Dashboard to generate a new token from.
    E.g. 'firebase', 'grafbase', or your custom template's name.

  • Name
    throwOnError?
    Type
    boolean
    Description

    Whether to throw an error or return an empty string, if an error occurs.

  • Name
    skipCache?
    Type
    boolean
    Description

    Whether to skip the cache lookup and force a call to the server instead, even within the TTL. Useful if the token claims are time-sensitive or depend on data that can be updated (e.g. user fields).
    Defaults to false.

  • Name
    organizationId?
    Type
    string
    Description

    The organization associated with the generated session token. Does not modify the session's currently active organization.

main.js
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) {
  await clerk.session
    .getToken({ template: 'Test' })
    .then((res) => console.log(res))
    .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)
}

checkAuthorization()

Checks if the user is authorized for the specified role or permission.

function checkAuthorization(param: CheckAuthorizationParams): boolean
type CheckAuthorizationParams =
  | {
      role: ClerkDefaultRole | CustomRole
      permission?: never
    }
  | {
      role?: never
      permission: ClerkDefaultPermission | CustomPermission
    }
  • Name
    role
    Type
    string
    Description

    Accepts role key

  • Name
    permission
    Type
    string
    Description

    Accepts permission key

  • Name
    reverification?
    Type
    ReverificationConfig
    Description

    The reverification configuration to check for.

startVerification()

Initiates the reverification flow. Returns a SessionVerification instance with its status and supported factors.

function startVerification(params: SessionVerifyCreateParams): Promise<SessionVerificationResource>
type SessionVerifyCreateParams = {
  status: 'pending' | 'verified' | 'failed'
}

prepareFirstFactorVerification()

Initiates the first factor verification process. This is a required step to complete a reverification flow when using a preparable factor. Returns a SessionVerification instance with its status and supported factors.

function prepareFirstFactorVerification(
  params: SessionVerifyPrepareFirstFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyPrepareFirstFactorParams = EmailCodeConfig | PhoneCodeConfig

type EmailCodeConfig = {
  strategy: 'email_code'
  primary?: boolean | undefined
  emailAddressId: string
}

type PhoneCodeConfig = {
  strategy: 'phone_code'
  phoneNumberId: string
  primary?: boolean
  default?: boolean
}

attemptFirstFactorVerification()

Attempts to complete the first factor verification process. Returns a SessionVerification instance with its status and supported factors.

function attemptFirstFactorVerification(
  params: SessionVerifyAttemptFirstFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyAttemptFirstFactorParams = EmailCodeAttempt | PhoneCodeAttempt | PasswordAttempt

type EmailCodeAttempt = {
  strategy: 'email_code'
  code: string
}

type PhoneCodeAttempt = {
  strategy: 'phone_code'
  code: string
}

type PasswordAttempt = {
  strategy: 'password'
  password: string
}

prepareSecondFactorVerification()

Initiates the second factor verification process. This is a required step to complete a reverification flow when using a preparable factor. Returns a SessionVerification instance with its status and supported factors.

function prepareSecondFactorVerification(
  params: SessionVerifyPrepareSecondFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyPrepareSecondFactorParams = PhoneCodeSecondFactorConfig

type PhoneCodeSecondFactorConfig = {
  strategy: 'phone_code'
  phoneNumberId?: string
}

attemptSecondFactorVerification()

Attempts to complete the second factor verification process. Returns a SessionVerification instance with its status and supported factors.

function attemptSecondFactorVerification(
  params: SessionVerifyAttemptSecondFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyAttemptSecondFactorParams = PhoneCodeAttempt | TOTPAttempt | BackupCodeAttempt

type PhoneCodeAttempt = {
  strategy: 'phone_code'
  code: string
}

type TOTPAttempt = {
  strategy: 'totp'
  code: string
}

type BackupCodeAttempt = {
  strategy: 'backup_code'
  code: string
}

Feedback

What did you think of this content?

Last updated on