Skip to main content

Session object

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.

The following example uses the useSession() hook to access the Session object. The Session object is used to access the lastActiveAt property, which is a Date object used to show the time the session was last active.

app/routes/index.tsx
import { useSession } from '@clerk/tanstack-react-start'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({
  component: HomePage,
})

function HomePage() {
  const { isLoaded, session, isSignedIn } = useSession()

  // Handle loading state
  if (!isLoaded) return <div>Loading...</div>

  // Protect the page from unauthenticated users
  if (!isSignedIn) return <div>Sign in to view this page</div>

  return (
    <div>
      <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>
    </div>
  )
}
  • Name
    abandonAt
    Type
    Date
    Description

    The date and time when the session was abandoned by the user.

  • Name
    actor
    Type
    null | { [x: string]: unknown; sub: string; type?: "agent"; }
    Description

    The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about impersonation.

  • Name
    agent
    Type
    null | { [x: string]: unknown; sub: string; type?: "agent"; } & { type: "agent"; }
    Description

    When the session's actor claim has type: 'agent', this property exposes information about the agent and Agent Task that was used to create the session.

  • Name
    createdAt
    Type
    Date
    Description

    The date and time when the session was first created.

  • Name
    currentTask?
    Type
    SessionTask
    Description

    The user's current pending session task.

  • Name
    expireAt
    Type
    Date
    Description

    The date and time when the session will expire.

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

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

  • Name
    id
    Type
    string
    Description

    The unique identifier for the session.

  • Name
    lastActiveAt
    Type
    Date
    Description

    The date and time when the session was last active on the Client.

  • Name
    lastActiveOrganizationId
    Type
    null | string
    Description

    The ID of the last .

  • Name
    lastActiveToken
    Type
    null | TokenResource
    Description

    The token that was last used to authenticate the session.

  • Name
    publicUserData
    Type
    PublicUserData
    Description

    Publicly available information about the current User.

  • Name
    status
    Type
    SessionStatus
    Description

    The current state of the session.

  • Name
    tasks
    Type
    null | SessionTask[]
    Description

    The user's pending session tasks.

  • Name
    updatedAt
    Type
    Date
    Description

    The date and time when the session was last updated.

  • Name
    user
    Type
    null | UserResource
    Description

    The User associated with the session.

Methods

attemptFirstFactorVerification()

Attempts to complete the process.

Returns a SessionVerification instance with its status and supported factors.

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

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

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

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

type PasskeyAttempt = {
  strategy: 'passkey'
  publicKeyCredential: PublicKeyCredentialWithAuthenticatorAssertionResponse
}

attemptSecondFactorVerification()

Attempts to complete the 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
}

checkAuthorization()

Checks if the user is authorized for the specified Role, Permission, Feature, or Plan or requires the user to reverify their credentials if their last verification is older than allowed.

function checkAuthorization(isAuthorizedParams: CheckAuthorizationParams): boolean
type WithReverification<T> = T & {
  /**
   * The reverification configuration to check for. This feature is currently in public beta. **It is not recommended for production use.** See https://clerk.com/docs/reference/backend/types/auth-object#reverification-config for more information.
   */
  reverification?: ReverificationConfig
}

type CheckAuthorizationParams = WithReverification<
  | {
      /**
       * The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to check for.
       */
      role: OrganizationCustomRoleKey
      /**
       * The [Permission](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to check for.
       */
      permission?: never
      /**
       * The [Feature](https://clerk.com/docs/guides/secure/features) to check for.
       */
      feature?: never
      /**
       * The [Plan](https://clerk.com/docs/guides/billing/overview) to check for.
       */
      plan?: never
    }
  | {
      role?: never
      permission: OrganizationPermissionKey
      feature?: never
      plan?: never
    }
  | {
      role?: never
      permission?: never
      feature: Autocomplete<`user:${string}` | `org:${string}`>
      plan?: never
    }
  | {
      role?: never
      permission?: never
      feature?: never
      plan: Autocomplete<`user:${string}` | `org:${string}`>
    }
  | { role?: never; permission?: never; feature?: never; plan?: never }
>

clearCache()

Clears the cache for the current session. This is useful if the session has been updated and the cache is no longer valid.

function clearCache(): void

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<SessionResource>

getToken()

Gets the current user's session token or a custom JWT 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. It retries on transient failures (e.g. network errors); when the browser is offline and retries are exhausted, it throws ClerkOfflineError.

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

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

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

  • 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
    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.

prepareFirstFactorVerification()

Initiates the 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(factor: SessionVerifyPrepareFirstFactorParams): Promise<SessionVerificationResource>
type SessionVerifyPrepareFirstFactorParams =
  | EmailCodeConfig
  | PhoneCodeConfig
  | PassKeyConfig
  | Omit<EnterpriseSSOConfig, 'actionCompleteRedirectUrl'>

type EmailCodeConfig = {
  /**
   * The strategy type.
   */
  strategy: 'email_code'
  /**
   * The ID of the email address used for the email code factor.
   */
  emailAddressId: string
  /**
   * Indicates whether the email address is set as the primary email address, as multiple can be added to a user's profile.
   */
  primary?: boolean
}

type PhoneCodeConfig = {
  /**
   * The strategy type.
   */
  strategy: 'phone_code'
  /**
   * The ID of the phone number used for the phone code factor.
   */
  phoneNumberId: string
  /**
   * Indicates whether the phone number is set as the primary phone number, as multiple can be added to a user's profile.
   */
  primary?: boolean
  /**
   * Indicates whether the phone number is set as the default identifier.
   */
  default?: boolean
  /**
   * The channel used for the phone code factor.
   */
  channel?: 'sms' | 'whatsapp'
}

type PassKeyConfig = {
  /**
   * The strategy type.
   */
  strategy: 'passkey'
}

type EnterpriseSSOConfig = {
  /**
   * The strategy type.
   */
  strategy: 'enterprise_sso'
  /**
   * The ID of the enterprise connection.
   * @experimental
   */
  enterpriseConnectionId?: string
  /**
   * The name of the enterprise connection.
   * @experimental
   */
  enterpriseConnectionName?: string
  /**
   * The URL to redirect to after the OAuth flow is completed.
   */
  redirectUrl: string
  /**
   * The OIDC prompt parameter to use for the OAuth flow.
   */
  oidcPrompt?: string
  /**
   * The ID of the email address used for the enterprise SSO factor.
   * @experimental
   */
  emailAddressId?: string
}

prepareSecondFactorVerification()

Initiates the 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: PhoneCodeSecondFactorConfig): Promise<SessionVerificationResource>
type PhoneCodeSecondFactorConfig = {
  /**
   * The strategy type.
   */
  strategy: 'phone_code'
  /**
   * The ID of the phone number used for the phone code second factor.
   */
  phoneNumberId?: string
}

remove()

Invalidates the current session by marking it as removed. Once removed, the session will be deactivated for the current Client instance and its status will be set to removed. This operation cannot be undone.

function remove(): Promise<SessionResource>

startVerification()

Initiates the reverification flow.

Returns a SessionVerification instance with its status and supported factors.

function startVerification(params: SessionVerifyCreateParams): Promise<SessionVerificationResource>
  • Name
    level
    Type
    "first_factor" | "second_factor" | "multi_factor"
    Description

    The level of the verification to create.

touch()

Updates the session's last active timestamp to the current time. This method should be called periodically to indicate ongoing user activity and prevent the session from becoming stale. The updated timestamp is used for session management and analytics purposes.

function touch(params?: SessionTouchParams): Promise<SessionResource>
  • Name
    intent?
    Type
    "focus" | "select_session" | "select_org"
    Description

    The intent of the touch operation.

verifyWithPasskey()

Initiates a verification flow using passkeys.

Returns a SessionVerification instance with its status and supported factors.

function verifyWithPasskey(): Promise<SessionVerificationResource>

Feedback

What did you think of this content?

Last updated on