
How to secure, monitor, and revoke user sessions with Clerk
List a user's active sessions with user.getSessions() or the active devices list in <UserProfile />. Revoke one device with session.revoke() or, on the server, clerkClient.sessions.revokeSession(). To sign a user out everywhere, loop over getSessionList() with revokeSession(), or pass signOutOfOtherSessions: true on a password change.
Wrap user-initiated revocations in useReverification(). A session token issued before a revocation keeps passing local verification for up to 60 seconds, so sensitive routes also need a live session check.
This part builds on the Next.js 16 Clerk quickstart and covers how users sign out their own devices, how admins revoke sessions and offboard accounts (with an Express version of the admin endpoint), and where the same controls live in the Clerk Dashboard. Plan details and Dashboard labels reflect Clerk's docs as of October 2026. For concepts such as session hijacking and fixation, and for an evaluation checklist, read the session management overview.
Why session invalidation is hard
Session invalidation, also called session revocation, ends a signed-in session before it expires so the credentials tied to it stop working. The Open Worldwide Application Security Project (OWASP) says to "invalidate the session on both sides, client and server. The latter is the most relevant and mandatory from a security perspective" (Session Management Cheat Sheet).
Without revocation:
- A lost or stolen laptop keeps access until its session expires. Mandiant's M-Trends 2026 says of harvested long-lived OAuth tokens and session cookies: "Because these often remain valid post-logout, attackers can hijack sessions without triggering MFA alerts." The fix is revoking that device.
- A password reset leaves an attacker's session alive, and OWASP recommends ending existing sessions after a reset (Forgot Password Cheat Sheet). The fix is signing out everywhere.
- An offboarded employee keeps working until their session ends. The fix is an offboarding action that ends sessions and blocks sign-in.
The JWT revocation problem. A JSON Web Token (JWT) is verified from its own signature with no server lookup, so "JWTs cannot be revoked due to their self-contained nature" (How Clerk works).
Session revocation and active-session visibility map to three requirements in the OWASP Application Security Verification Standard (ASVS) 5.0.0 (V7): v5.0.0-7.5.2 (users view and end their sessions after authenticating again), v5.0.0-7.4.3 (offer to end other sessions after a factor change), and v5.0.0-7.4.5 (admins end a user's sessions).
Approaches to multi-device session management and revocation
Each design trades per-request cost against revocation delay:
OWASP's Top 10:2025 advises: "Ideally, use a premade, well-trusted system to handle authentication, identity, and session management" (A07:2025).
How Clerk session management works
How Clerk works documents Clerk's full authentication model. Three parts of it determine how revocation behaves.
Clients, sessions, and multi-session apps
A client is one browser or device, and Clerk's Client object "keeps track of the authenticated sessions in the current device." A session is one signed-in account on that client, so a user on a laptop and a phone has two clients with one session each.
A multi-session application "allows multiple accounts to be signed in from the same browser at the same time" (session options). Multi-device sign-in works in either mode, because the multi-session setting governs accounts within one browser.
To enable multi-session apps, in the Clerk Dashboard, navigate to the Sessions page and turn on Multi-session handling. Multi-session apps ("Simultaneous sessions" on the pricing page) are included in the Pro, Business, and Enterprise plans.
Only active and pending sessions are still open. A pending session has unfinished session tasks, and Clerk treats it as signed out. The other six SessionStatus values, such as revoked, ended, and expired, mark finished sessions.
Session lifetime and inactivity timeout
For web browser sessions, the maximum lifetime defaults to 7 days and the inactivity timeout is off. "Either one or both must be enabled at all times" (session options).
To set them, in the Clerk Dashboard, navigate to the Sessions page, or run clerk config patch under session_settings. A custom maximum lifetime and the inactivity timeout need a paid plan for production use and are free in development. Hobby production instances keep a fixed 7-day lifetime (pricing).
Choosing a session lifetime is "a trade-off between security and user experience" (session options). A shorter maximum lifetime or inactivity timeout limits exposure from a forgotten or stolen device but makes users sign in more often. Neither setting changes the revocation window.
For reference points, OWASP says "Common idle timeouts ranges are 2-5 minutes for high-value applications and 15-30 minutes for low risk applications" (Session Management Cheat Sheet). The National Institute of Standards and Technology (NIST) SP 800-63B-4 says the overall reauthentication timeout SHOULD be no more than 24 hours at authenticator assurance level 2 (AAL2) and SHALL be no more than 12 hours at AAL3. Its inactivity timeouts SHOULD be no more than 1 hour at AAL2 and 15 minutes at AAL3.
The 60-second session token and the revocation window
Clerk splits a signed-in session across two tokens (How Clerk works). In production, the long-lived client token sits in an HttpOnly __client cookie on the Frontend API domain and is "the source of truth for authentication state" (client token). The session token is a JWT in the __session cookie "that expires after 60 seconds," and Clerk's frontend SDKs refresh it on a 50-second interval.
In Next.js, clerkMiddleware() verifies the session token's signature and expiry locally for auth(), without asking Clerk whether the session is still active. authenticateRequest() is "Networkless if the jwtKey is provided."
After you revoke a session, Clerk stops issuing session tokens for it, but a token issued before the revocation keeps passing local verification until it expires, up to 60 seconds later by default. The revoked browser signs out at its next refresh. This revocation window is the trade-off for fast, local verification on every request.
JWT template tokens and Backend API tokens created with a longer expires_in_seconds (Backend API spec) outlive a revocation until their own expiry. For sensitive actions, Part 2 adds a live session check that closes the window.
Let users see and sign out their own devices
Multi-device session management starts with a page where users list their active sessions and sign out any device they don't recognize. Clerk ships a drop-in component and the APIs to build your own.
Drop-in: the active devices list in <UserProfile />
In the quickstart, selecting Manage account in <UserButton /> opens <UserProfile />. Its Security page lists Active devices: each device's type, browser and version, IP address with city and country, and last active time, with a "This device" badge on the current one (<UserButton />, source).
Every other device's three-dot menu has Sign out of device (source). Every Clerk plan, Hobby included, has device tracking and revocation (pricing).
Clerk requires a recent sign-in or reverification before a device sign-out, since "Revoke session" is a protected sensitive action. The password form on the same page has a Sign out of all other devices checkbox, checked by default (source).
To give the profile its own page, render <UserProfile /> on an optional catch-all route. The component reads the URL from the request, so wrap it in <Suspense>. Without the boundary, next build fails in apps that use Cache Components, which the quickstart enables:
import { UserProfile } from '@clerk/nextjs'
import { Suspense } from 'react'
export default function UserProfilePage() {
return (
<Suspense>
<UserProfile />
</Suspense>
)
}Then pass userProfileMode="navigation" and userProfileUrl="/user-profile" to <UserButton /> so Manage account navigates to /user-profile.
List active sessions with user.getSessions()
For your own UI, user.getSessions() "Gets all active sessions for this user" (User object). Each SessionWithActivities has id, status, lastActiveAt, expireAt, abandonAt, and a latestActivity object with the fields browserName, browserVersion, deviceType, isMobile, ipAddress, city, and country. This client component lists them and marks the current device:
'use client'
import { useReverification, useSession, useUser } from '@clerk/nextjs'
import { isClerkAPIResponseError, isReverificationCancelledError } from '@clerk/nextjs/errors'
import type { SessionWithActivitiesResource } from '@clerk/nextjs/types'
import { useEffect, useState } from 'react'
export function ActiveDevices() {
const { user } = useUser()
const { session: current } = useSession()
const [sessions, setSessions] = useState<SessionWithActivitiesResource[]>([])
useEffect(() => {
if (!user) return
let ignore = false
user.getSessions().then((list) => {
if (!ignore) setSessions(list)
})
return () => {
ignore = true
}
}, [user])
// Paste the hooks and handlers from the next two sections here
return (
<div>
<ul>
{sessions.map((s) => {
const a = s.latestActivity
return (
<li key={s.id}>
{a.browserName} {a.browserVersion} ({a.isMobile ? 'mobile' : a.deviceType})
<br />
{a.city}, {a.country} ({a.ipAddress})
<br />
Last active {s.lastActiveAt.toLocaleString()}
{s.id === current?.id ? (
<strong> This device</strong>
) : (
<button onClick={() => signOutDevice(s)}>Sign out of device</button>
)}
</li>
)
})}
</ul>
{sessions.length > 1 && (
<button onClick={signOutOtherDevices}>Sign out of other listed devices</button>
)}
</div>
)
}Render <ActiveDevices /> on any signed-in page, such as app/devices/page.tsx. Clerk resolves city and country by IP address geolocation, so treat them as approximate (SessionActivity). There's no operating-system field, so branch on isMobile and use deviceType as a display label.
getSessions() uses a cache (source), so the component keeps the list in React state and updates it after each revocation. The ignore flag drops a response that arrives after the user switches accounts in a multi-session app. In multi-session apps, useSessionList() returns the sessions registered on this browser, while user.getSessions() returns the user's active sessions across devices.
Revoke one device with session.revoke()
revoke() ends the session it's called on, with two limits: "If this is the active session, the attempt to revoke it will fail. Users can revoke only their own sessions" (revoke()). The component hides the button on the current device, where signOut() applies.
Once the reverification window passes (10 minutes by default), a revoke request fails with session_reverification_required until the user verifies again. useReverification() shows Clerk's prompt and retries the call, so wrap every custom revoke() call in it:
const revokeDevice = useReverification((s: SessionWithActivitiesResource) => s.revoke())
async function signOutDevice(s: SessionWithActivitiesResource) {
try {
const revoked = await revokeDevice(s)
if (revoked.status === 'revoked') {
setSessions((prev) => prev.filter((p) => p.id !== s.id))
}
} catch (err) {
if (isReverificationCancelledError(err)) return
console.error(err)
}
}If the browser is offline, the request fails without an error and revoke() resolves with the session unchanged (source), so the device stays listed and the user can try again.
Canceling the prompt rejects the call with a ClerkRuntimeError coded reverification_cancelled (source). Catch it with isReverificationCancelledError() from @clerk/nextjs/errors and return quietly. Log any other error, since rethrowing from a click handler leaves an unhandled rejection.
Sign out of all other devices
Skip the current session, and keep sessions whose status is active or pending (Clerk's own list shows both). Revoke them with Promise.allSettled inside one useReverification() wrapper. That way, the user sees one prompt, and the hook then retries the callback once:
const revokeOtherDevices = useReverification(async () => {
const others = sessions.filter(
(s) => s.id !== current?.id && (s.status === 'active' || s.status === 'pending'),
)
const results = await Promise.allSettled(others.map((s) => s.revoke()))
const revokedIds = results.flatMap((r) =>
r.status === 'fulfilled' && r.value.status === 'revoked' ? [r.value.id] : [],
)
setSessions((prev) => prev.filter((s) => !revokedIds.includes(s.id)))
const errors = results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []))
const failed =
errors.find(
(e) =>
isClerkAPIResponseError(e) &&
e.errors.some((x) => x.code === 'session_reverification_required'),
) ?? errors[0]
if (failed) throw failed
})
async function signOutOtherDevices() {
try {
await revokeOtherDevices()
} catch (err) {
if (isReverificationCancelledError(err)) return
console.error(err)
}
}The hook prompts only for a session_reverification_required error and rethrows anything else (source). Rethrowing that error ahead of other failures means a network error on one device can't hide the prompt, and the retry covers only the devices left.
The button renders only once another device is listed, and it signs out the devices that getSessions() loaded when the page opened. For sessions created after the page loaded, use the backend revokeAllSessions() helper.
signOut() ends the session in the current browser. The user's sessions on other devices stay active until you revoke them with session.revoke() or revokeSession() (sign-out guide). To sign a user out of every listed device from the browser, revoke the other sessions, then call signOut().
Multi-session apps: signOut({ sessionId }) vs. signOut()
In a multi-session app, signOut({ sessionId }) from the Clerk object signs out one account in this browser, and signOut() signs out every account in this browser. Neither touches other devices.
Custom signOut() calls redirect to their redirectUrl option or the afterSignOutUrl prop on <ClerkProvider>. Prebuilt components use the afterMultiSessionSingleSignOutUrl prop on <ClerkProvider> when other accounts stay signed in (source).
Manage and revoke user sessions from the backend
Backend API calls can revoke any user's sessions, so every admin route in this section runs server-side and checks the caller's authorization inside the handler. Clerk's clerkMiddleware() reference says to "protect access as close to the resource as possible, in the code that reads or mutates the data."
The examples use Clerk's Basic role-based access control (RBAC) pattern for apps that, like the quickstart, don't use Organizations (Basic RBAC). Apps on Organizations can check has({ permission }) instead (authorization checks).
To set it up:
- In the Clerk Dashboard, navigate to the Sessions page. Under Customize session token, add
{ "metadata": "{{user.public_metadata}}" }to the session token's claims in the Claims editor and select Save. - Declare
CustomJwtSessionClaimsintypes/globals.d.tsas the Basic RBAC guide shows. - To make yourself an admin, in the Clerk Dashboard, navigate to the Users page and select your account. Select Edit next to Public in the User metadata section, add
{ "role": "admin" }, and select Save.
Without that role, the admin routes below return 403 to every signed-in caller. Session-token claims can lag the underlying data by up to 60 seconds (customize session tokens), so the highest-impact route re-reads the caller with users.getUser().
List a user's active sessions with getSessionList()
For an admin or support view, this route returns a user's active sessions with the same device details the client SDK exposes:
import { auth, clerkClient } from '@clerk/nextjs/server'
import { NextResponse, type NextRequest } from 'next/server'
type Context = { params: Promise<{ userId: string }> }
export async function GET(_req: NextRequest, { params }: Context) {
const { isAuthenticated, sessionClaims } = await auth()
if (!isAuthenticated) {
return NextResponse.json({ error: 'Unauthenticated' }, { status: 401 })
}
if (sessionClaims?.metadata?.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const { userId } = await params
const client = await clerkClient()
const { data, totalCount } = await client.sessions.getSessionList({
userId,
status: 'active',
limit: 100,
})
const sessions = data.map((s) => ({
id: s.id,
lastActiveAt: s.lastActiveAt,
impersonated: s.actor !== null && s.actor.type !== 'agent',
activity: s.latestActivity,
}))
return NextResponse.json({ sessions, totalCount })
}getSessionList() "Requires either clientId or userId" and returns { data, totalCount }, newest first. limit defaults to 10 and goes up to 500 (getSessionList()). "Old and inactive sessions are periodically cleaned up" (API spec), so the list omits them.
A non-null actor marks an impersonation session (Session) or, when actor.type is 'agent', an Agent Task session (agent). Flag impersonations in admin views.
Revoke one session with revokeSession()
await client.sessions.revokeSession(sessionId) "Revokes the given session. The user will be signed out from the client the session is associated with" (revokeSession()). The status becomes revoked, "an unauthenticated state" (API spec), and the device loses access within the revocation window.
Sign out everywhere: revoke sessions after a password reset or suspected compromise
To sign a user out of all devices, revoke every active or pending session. Two of the three common cases need no loop.
Password changes. Pass signOutOfOtherSessions: true. On the client, call user.updatePassword() inside useReverification() (update password flow). On the backend, users.updateUser(userId, { password, signOutOfOtherSessions: true }) accepts the flag only with a new password (updateUser(), API spec).
In the Core 3 reset flow from useSignIn(), call signIn.resetPasswordEmailCode.submitPassword({ password, signOutOfOtherSessions: true }), then call signIn.finalize() once signIn.status is 'complete' (forgot password flow). If the status is 'needs_second_factor', complete the multi-factor flow before finalizing.
Suspected compromise. users.setPasswordCompromised(userId, { revokeAllSessions: true }) revokes every session and prompts a password reset at the next sign-in (setPasswordCompromised()). New instances have the reset-password session task on by default. For older instances, in the Clerk Dashboard, navigate to the Updates page and turn on the Reset password session task update (password protection, changelog).
No password, or no forced reset. Page through getSessionList() and revoke each session. This helper lists without a status filter and keeps active and pending sessions, so sessions with unfinished tasks end too.
Revoking leaves sign-in open, and the scan is best-effort: a sign-in or Clerk's cleanup of old sessions mid-scan can make it miss one. Lock the user first, or ban them when every session must end, since banUser() revokes all of them server-side (API spec):
import type { clerkClient } from '@clerk/nextjs/server'
type ClerkClient = Awaited<ReturnType<typeof clerkClient>>
export async function revokeAllSessions(client: ClerkClient, userId: string) {
const ids: string[] = []
let offset = 0
while (true) {
const { data, totalCount } = await client.sessions.getSessionList({
userId,
limit: 500,
offset,
})
for (const s of data) {
if (s.status === 'active' || s.status === 'pending') ids.push(s.id)
}
offset += data.length
if (!data.length || offset >= totalCount) break
}
for (const id of ids) {
await client.sessions.revokeSession(id)
}
return ids.length
}The helper revokes one session at a time to keep the request rate low. The Backend API rate limits are 1,000 requests per 10 seconds on production instances and 100 on development instances (Clerk rate limits).
Backend API calls run with your secret key, so reverification is your route's job. Add this DELETE handler to the same route file. The role check runs before reverification, so non-admins get a 403 without a prompt. Part 2 explains how the client handles the reverification 403:
import { auth, clerkClient, reverificationErrorResponse } from '@clerk/nextjs/server'
import { NextResponse, type NextRequest } from 'next/server'
import { revokeAllSessions } from '@/lib/revoke-all-sessions'
// Keep the Context type and GET handler from above
export async function DELETE(_req: NextRequest, { params }: Context) {
const { isAuthenticated, userId: callerId, sessionId, sessionClaims, has } = await auth()
if (!isAuthenticated) {
return NextResponse.json({ error: 'Unauthenticated' }, { status: 401 })
}
if (sessionClaims?.metadata?.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
if (!has({ reverification: 'strict' })) {
return reverificationErrorResponse('strict')
}
// Live session check: the token can be up to 60 seconds behind a revocation or role change
const client = await clerkClient()
const [session, caller] = await Promise.all([
client.sessions.getSession(sessionId).catch(() => null),
client.users.getUser(callerId).catch(() => null),
])
if (session?.status !== 'active') {
return NextResponse.json({ error: 'Session ended' }, { status: 401 })
}
if (caller?.publicMetadata.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const { userId } = await params
const revoked = await revokeAllSessions(client, userId)
return NextResponse.json({ revoked })
}Express version of the revoke-all endpoint
Backend-only apps can run the same revoke-all endpoint on Express with @clerk/express (Express quickstart). Install the packages:
npm install express @clerk/express @clerk/shared
npm install -D tsx @types/expressRegister clerkMiddleware() before any other middleware, then read the caller with getAuth(req). The handler runs the same checks as the Next.js DELETE handler. @clerk/express doesn't export reverificationError, so the handler imports it from @clerk/shared/authorization-errors (reverification guide):
import { clerkClient, clerkMiddleware, getAuth } from '@clerk/express'
import { reverificationError } from '@clerk/shared/authorization-errors'
import express from 'express'
import { revokeAllSessions } from './lib/revoke-all-sessions.js'
const app = express()
app.use(clerkMiddleware())
app.delete('/admin/users/:userId/sessions', async (req, res) => {
const { isAuthenticated, userId: callerId, sessionId, sessionClaims, has } = getAuth(req)
if (!isAuthenticated) {
res.status(401).json({ error: 'Unauthenticated' })
return
}
if (sessionClaims?.metadata?.role !== 'admin') {
res.status(403).json({ error: 'Forbidden' })
return
}
if (!has({ reverification: 'strict' })) {
res.status(403).json(reverificationError('strict'))
return
}
const [session, caller] = await Promise.all([
clerkClient.sessions.getSession(sessionId).catch(() => null),
clerkClient.users.getUser(callerId).catch(() => null),
])
if (session?.status !== 'active') {
res.status(401).json({ error: 'Session ended' })
return
}
if (caller?.publicMetadata.role !== 'admin') {
res.status(403).json({ error: 'Forbidden' })
return
}
const revoked = await revokeAllSessions(clerkClient, req.params.userId)
res.json({ revoked })
})
app.listen(3000)To finish the setup:
- Copy the
revokeAllSessions()helper tolib/revoke-all-sessions.tsand replace itsclerkClientimport andClerkClienttype alias withimport type { ClerkClient } from '@clerk/express'. - Add the Basic RBAC guide's
CustomJwtSessionClaimsdeclaration (types/globals.d.ts) so the role check type-checks. - Locally, run
npx tsx --env-file=.env server.tson Node 20.9 or later. In production, drop--env-fileand set your production API keys as host environment variables (quickstartpackage.json,@clerk/express). In ECMAScript module (ESM) projects, keep the helper import's.jsextension.
Offboarding: what ban, lock, delete, and SCIM deprovisioning do to sessions
To offboard a user, end their existing sessions and block new sign-ins:
User bans are included in Clerk's Pro, Business, and Enterprise plans (pricing).
SCIM deprovisioning happens once the identity provider syncs the change, "which can take several minutes" (Directory Sync). A user in several directories needs deprovisioning in every enabled one (multiple directories, changelog). EASIE deprovisioning (Google and Microsoft connections) revokes sessions after "a delay of up to 10 minutes" (enterprise connections).
Multi-factor authentication (MFA) resets and blocklist changes leave sessions active (MFA recovery, changelog). For SCIM setup and audit trails, see HR-driven offboarding for B2B SaaS.
Manage sessions in the Clerk Dashboard
Support teams can revoke sessions and ban, lock, or delete a user without code from the user's profile page. In the Clerk Dashboard, navigate to the Users page, select the user, and go to the Devices section.
Each device's three-dot menu has Revoke device, and Revoke all devices sits at the bottom when 2 or more devices are listed. The Actions menu has Ban user, Lock user, Unlock user, and Delete user.
The same page has Set password as compromised in the Password section's three-dot menu, with an option to sign the user out of all active sessions (password protection, changelog). Impersonate user is in the three-dot menu on the user's row on the Users page (impersonation).
To lock accounts after failed sign-ins, in the Clerk Dashboard, navigate to the Protect → Sign-in security page and turn on account lockout (lockout settings).
Admin Logs record admin actions such as session revocations, bans, and locks. They're available on the Business and Enterprise plans (plans and retention).
FAQ
Next steps: protect sensitive actions and monitor sessions
Part 2 covers reverification and the live session check for sensitive actions, multi-device login tracking with session webhooks and Application Logs, and a comparison of Clerk, WorkOS, Auth0, and Supabase.
In this series
- How to secure, monitor, and revoke user sessions with Clerk (you are here)
- How to secure, monitor, and revoke user sessions with Clerk - Part 2