Skip to main content
Docs

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/(session)/page.tsx
import { useSession } from '@clerk/expo'
import { Text, View } from 'react-native'

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

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

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

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

    The time when the session was abandoned by the user.

  • Name
    actor
    Type
    ActJWTClaim | null
    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
    AgentActClaim | null
    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 when the session was created.

  • Name
    currentTask
    Type
    SessionTask | undefined
    Description

    The current pending task for the session. Read more about session tasks.

  • Name
    expireAt
    Type
    Date
    Description

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

  • 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
    id
    Type
    string
    Description

    The unique identifier for the session.

  • Name
    lastActiveAt
    Type
    Date
    Description

    The time the session was last active on the Client.

  • Name
    lastActiveOrganizationId
    Type
    string | null
    Description

    The ID of the last .

  • Name
    lastActiveToken
    Type
    TokenResource | null
    Description

    The last active token for 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
    tasks
    Type
    SessionTask[] | null
    Description

    The pending tasks for the session.

  • Name
    updatedAt
    Type
    Date
    Description

    The last time the session recorded activity of any kind.

  • Name
    user
    Type
    User | null
    Description

    The user associated with the session, or null if none.

Methods

attemptFirstFactorVerification()

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

function attemptFirstFactorVerification(
  params: 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: PublicKeyCredential
}

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(param: 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.**
   */
  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/billing/overview) 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 }
>
  • Name
    role
    Type
    string
    Description

    Accepts Role key.

  • Name
    permission
    Type
    string
    Description

    Accepts Permission key.

  • Name
    feature
    Type
    string
    Description

    Accepts Feature key.

  • Name
    plan
    Type
    string
    Description

    Accepts Plan key.

  • Name
    reverification?
    Type
    ReverificationConfigClerk Icon
    Description

    The reverification configuration to check for. This feature is currently in public beta. It is not recommended for production use.

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()

Terminates the current session, invalidating it for this Client instance. Upon completion, the session's status transitions to ended and all associated authentication tokens are revoked. This operation cannot be undone and requires re-authentication to establish a new session.

function end(): Promise<Session>

getToken()

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

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(
  params: SessionVerifyPrepareFirstFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyPrepareFirstFactorParams =
  | EmailCodeConfig
  | PhoneCodeConfig
  | PasskeyConfig
  | EnterpriseSSOConfig

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

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

type PasskeyConfig = {
  strategy: 'passkey'
}

type EnterpriseSSOConfig = {
  strategy: 'enterprise_sso'
  emailAddressId: string
  enterpriseConnectionId: string
  redirectUrl: 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: SessionVerifyPrepareSecondFactorParams,
): Promise<SessionVerificationResource>
type SessionVerifyPrepareSecondFactorParams = PhoneCodeSecondFactorConfig

type PhoneCodeSecondFactorConfig = {
  strategy: 'phone_code'
  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<Session>

startVerification()

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

function startVerification(params: SessionVerifyCreateParams): Promise<SessionVerificationResource>
type SessionVerifyCreateParams = {
  level: 'first_factor' | 'second_factor' | 'multi_factor'
}

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(): Promise<Session>

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