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.
The following example uses the useSession() composable 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.
<script setup>
import { useSession } from '@clerk/vue'
const { isLoaded, session, isSignedIn } = useSession()
</script>
<template>
<div v-if="!isLoaded">
<!-- Handle loading state -->
</div>
<div v-else-if="!isSignedIn">
<!-- Handle signed out state -->
</div>
<div v-else>
<p>This session has been active since {{ session.lastActiveAt.toLocaleString() }}</p>
</div>
</template>- 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
-
currentTask? - Type
- SessionTask
- Description
The user's current pending session task.
- Name
-
lastActiveAt - Type
Date- Description
The date and time when the session was last active on the Client.
- 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
-
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): booleantype 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(): voidend()
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
-
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>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>verifyWithPasskey()
Initiates a verification flow using passkeys.
Returns a SessionVerification instance with its status and supported factors.
function verifyWithPasskey(): Promise<SessionVerificationResource>Feedback
Last updated on