Skip to main content
Articles

How to secure, monitor, and revoke user sessions with Clerk - Part 2

Author: Roy Anger
Published:

Guard each sensitive action with reverification, Clerk's form of step-up authentication. When has({ reverification }) fails at the level the action needs, return reverificationErrorResponse() with that same level from the route handler, and wrap the client call in useReverification(), which shows Clerk's prompt and retries the request.

On irreversible or high-impact routes, also run a live session check: confirm that getSession() still reports the session as active. To monitor sessions, verify session.* webhooks with verifyWebhook() and review Application Logs in the Clerk Dashboard.

This part builds on the Next.js 16 Clerk quickstart and covers reverification levels, the live session check that closes the revocation window from Part 1, session webhooks, Clerk's new-device protections, Application Logs, and a comparison of session management tools. Vendor and plan details reflect public docs as of October 2026.

Note

Tested on November 19, 2026 with next 16.4.6 and @clerk/nextjs 7.10.5, which pulls in @clerk/backend 3.31.2 (release notes). The webhook handler's evt.timestamp needs @clerk/nextjs 7.9.8 or later (release notes), and the quickstart's lockfile resolves @clerk/nextjs 7.9.17 and next 16.4.2, so update @clerk/nextjs and next first.

Protect sensitive actions with step-up authentication (reverification)

How reverification differs from revocation

Reverification checks how recently a user verified their credentials, while revocation ends a session. Reverification reads the session token's fva claim, which holds the minutes since the user last verified a first factor and the minutes since they last verified a second factor (session tokens).

Because the check reads only the token, a token issued before a revocation still passes has({ reverification }) until it expires. The check also measures only freshness, so one reverification approves every request inside the window. Pair reverification with a live session check on the most sensitive routes.

Clerk requires reverification for 11 sensitive actions, including "Revoke session" and "Set/update password," with a 10-minute default window, and its prebuilt components handle the prompt (sensitive actions). To change the window, in the Clerk Dashboard, navigate to the Sessions page and set Session lifetime → Reverification window to a value from 1 to 10 minutes (changelog). The setting "applies only to the Clerk-protected sensitive actions" (customize the window).

Important

Applications created before March 31, 2025, need one more step (changelog). In the Clerk Dashboard, navigate to the Updates page and turn on the Reverification APIs.

Choose a reverification level

has() accepts four preset levels or a custom { level, afterMinutes } object (ReverificationConfig, preset values). The "Suggested use" column is this article's recommendation.

LevelVerified withinFactor Clerk asks forSuggested use
strict_mfa10 minutesFirst and second factorIrreversible or high-value actions, such as deleting data or changing billing
strict10 minutesSecond factorSigning out devices, revoking sessions, account changes
moderate1 hourSecond factorLower-risk account actions
lax1 daySecond factorLow-risk actions
Custom { level, afterMinutes }afterMinutesfirst_factor, second_factor, or multi_factorYour own policy

Reverification accepts password, email code, phone code, passkey, and Enterprise single sign-on (SSO) as first factors. Its second factors are phone code, authenticator app, and backup code, plus passkey on API version 2026-08-20 or later when Passkeys satisfy multi-factor authentication is on (conditions).

When a user has no second factor, the level falls back to first_factor. Users with no eligible factor, such as those who sign in only with email links, can't reverify (caveats). Multi-factor authentication (MFA) needs a paid plan for production use (MFA), so on a Hobby production instance every level checks the first factor.

Close the revocation window with a live session check

Match each request to the checks it needs:

Request typeChecksWhy
Ordinary reads and writesauth() onlyLocal token verification, no session lookup
Account changes, signing out other devices, admin changesauth() plus reverificationProves a recent verification
Irreversible or high-impact actions: deleting or exporting data, changing billing, revoking another user's sessionsauth(), reverification, and a live getSession(sessionId) check that status === 'active'Closes the 60-second revocation window

Reverification and the live session check run only on sensitive actions, so everyday requests stay fast and skip the Backend API getSession() call, which counts toward Clerk's rate limits.

Put both checks in the route handler or Server Action body. Next.js layouts "don't re-render on navigation, meaning the user session won't be checked on every route change" (layouts), and Proxy should "only read the session from the cookie (optimistic checks), and avoid database checks" (Proxy). Keep auth() and the live session check outside 'use cache' scopes, which can't read cookies() or headers().

Example: a route handler with both checks

Every check runs before deleteProject(), which stands in for your own data layer, so no data changes until the live session check confirms the session is still active. A stale verification gets the 403 (source) that useReverification() turns into a prompt on the client:

app/api/projects/[id]/route.ts
import { auth, clerkClient, reverificationErrorResponse } from '@clerk/nextjs/server'
import { NextResponse, type NextRequest } from 'next/server'
import { deleteProject } from '@/lib/projects'

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { isAuthenticated, userId, sessionId, has } = await auth()
  if (!isAuthenticated) {
    return NextResponse.json({ error: 'Unauthenticated' }, { status: 401 })
  }

  // Step-up: strict_mfa reverification (verified in the last 10 minutes)
  if (!has({ reverification: 'strict_mfa' })) {
    return reverificationErrorResponse('strict_mfa')
  }

  // Live check: the session hasn't been revoked since this token was issued
  const client = await clerkClient()
  const session = await client.sessions.getSession(sessionId).catch(() => null)
  if (session?.status !== 'active') {
    return NextResponse.json({ error: 'Session ended' }, { status: 401 })
  }

  const { id } = await params
  await deleteProject(id, userId)
  return NextResponse.json({ deleted: id })
}

getSession() throws when the Backend API call fails, including the 404 for a session that no longer exists. .catch(() => null) routes a failed lookup to the same JSON 401, so the route fails closed.

In a Server Action, return reverificationError('strict_mfa') instead (Server Action example). reverificationError() returns the same error as a plain object rather than a 403 Response, and both helpers come from @clerk/nextjs/server.

Keep reverification in its own has() call. Combining it with role, permission, feature, or plan in one call was the subject of security advisory GHSA-w24r-5266-9c3c, fixed in @clerk/nextjs 7.2.4.

Prompt and retry on the client with useReverification()

useReverification() catches the 403, shows Clerk's verification prompt, and after the user verifies, "the original request will automatically retry." This button calls the route above:

app/projects/delete-project-button.tsx
'use client'

import { useReverification } from '@clerk/nextjs'
import { isReverificationCancelledError } from '@clerk/nextjs/errors'

type DeleteResult = { deleted: string } | { error: string }

export function DeleteProjectButton({ id }: { id: string }) {
  const deleteProject = useReverification(async (): Promise<DeleteResult> => {
    const res = await fetch(`/api/projects/${id}`, { method: 'DELETE' })
    return res.json()
  })

  async function handleClick() {
    try {
      const result = await deleteProject()
      if ('error' in result) console.error(result.error)
    } catch (err) {
      if (isReverificationCancelledError(err)) return
      console.error(err)
    }
  }

  return <button onClick={handleClick}>Delete project</button>
}

Return JSON from every branch of the route, and check the body for an error. The hook resolves with the parsed body, JSON 4xx and 5xx responses included, while a text body or an empty 204 makes res.json() throw a SyntaxError (source). The fetcher returns typed res.json() without checking res.ok, since throwing there would hide the 403 that triggers the prompt.

Part 1 shows useReverification() wrapping a batch of session.revoke() calls. For a custom prompt UI, use the hook's onNeedsReverification option.

Track sign-ins across devices with session webhooks and Application Logs

Session webhooks push events into your own alerting and audit systems, though delivery isn't guaranteed. Clerk's new-device protections warn or challenge the user at sign-in with no code, and Application Logs let you investigate afterward from the Dashboard or a terminal.

Session webhook events

Clerk's backend software development kit (SDK) defines four session.* webhook event types (event types), each matching a session status (SessionStatus):

EventMatching session status (Clerk's definition)
session.createdactive: "The session is valid and all activity is allowed."
session.endedended: the user signed out, "but the Session remains in the Client object"
session.removedremoved: the user signed out "and the Session was removed from the Client object"
session.revokedrevoked: "The application ended the session and the Session was removed from the Client object."

To subscribe, in the Clerk Dashboard, navigate to the Webhooks page. Its Event Catalog lists every supported event (webhooks overview).

For offboarding audits, also subscribe to user.updated and user.deleted. The user.updated payload carries the user's banned and locked flags (webhook spec), plus deprovisioned after System for Cross-domain Identity Management (SCIM) deprovisioning (Directory Sync). The offboarding table in Part 1 lists the audit signal each action leaves.

Use session webhooks for audit logs and alerts, and keep access decisions in auth(), reverification, and live session checks. Clerk's webhooks are "not guaranteed to be delivered immediately or at all" (webhooks overview).

Delivery is at least once, with retries until your endpoint returns a 2xx or the retry schedule ends. Clerk's docs add that events "aren't guaranteed to arrive in the order they occurred" (ordering).

Every retry carries the same svix-id, so deduplicate on it (duplicates). Respond within "a reasonable time-frame (15s with Svix)" (Svix retries). The Open Worldwide Application Security Project (OWASP) recommends logging the session lifecycle: applications should "record session related events, such as the creation, renewal, and destruction of session IDs" (Session Management Cheat Sheet).

Verify session webhooks in a Next.js route handler

Verify each delivery with verifyWebhook() from @clerk/nextjs/webhooks, which reads your signing secret from CLERK_WEBHOOK_SIGNING_SECRET, then log only the fields you need (syncing guide):

app/api/webhooks/route.ts
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import type { NextRequest } from 'next/server'

export async function POST(req: NextRequest) {
  try {
    const evt = await verifyWebhook(req)

    switch (evt.type) {
      case 'session.created':
      case 'session.ended':
      case 'session.removed':
      case 'session.revoked':
        console.info('Clerk session event', {
          svixId: req.headers.get('svix-id'),
          type: evt.type,
          timestamp: evt.timestamp,
          userId: evt.data.user_id,
          status: evt.data.status,
        })
        break
    }

    return new Response('OK', { status: 200 })
  } catch (err) {
    console.error('Webhook verification failed', err)
    return new Response('Webhook verification failed', { status: 400 })
  }
}

Clerk retries any delivery that doesn't get a 2xx, so an event that fails verification while CLERK_WEBHOOK_SIGNING_SECRET is wrong can still arrive on a later attempt in the retry schedule once you fix it.

evt.timestamp is the "timestamp in milliseconds of when the event occurred" (payload structure), so an audit trail can sort events by occurrence time, regardless of arrival order. evt.data keeps the payload's snake_case keys, such as user_id, unlike the camelCase backend Session object (userId) that getSession() returns (webhook spec).

The payload carries the full user object (webhook spec), so log only the fields you need. OWASP says session identification values "should usually not be recorded directly in the logs, but instead should be removed, masked, sanitized, hashed, or encrypted" (Logging Cheat Sheet). Hash the session ID if you need to correlate events.

The quickstart's proxy.ts exports clerkMiddleware(), which leaves this route public: "By default, clerkMiddleware() doesn't protect any routes" (public route). If your Proxy protects routes, exclude /api/webhooks.

To test locally, run clerk webhooks listen with --forward-to set to your local /api/webhooks URL. It opens a relay tunnel to your handler (Clerk CLI changelog). In the Clerk Dashboard, navigate to the Webhooks page, add the relay URL it prints as an endpoint, and set CLERK_WEBHOOK_SIGNING_SECRET to that endpoint's signing secret (Clerk's webhooks agent skill).

Built-in new-device protection: sign-in emails and Device Trust

When someone signs in from an unfamiliar device, Clerk emails the account owner with details "such as device type, operating system, IP address, location, and the sign-in method used" (unauthorized sign-ins). "For supported instances, the email might also include a button that allows users to sign out from the unrecognized device." That sign-out option needs a paid plan for production use (revoke sessions).

Since March 20, 2025, the email has been on by default for new apps, while older apps opt in (changelog). To edit its Sign in from new device template, in the Clerk Dashboard, navigate to the Emails page.

Device Trust asks for a second factor when a user without MFA signs in from a new device, and it "only applies to password-based sign-ins" (Device Trust). It's on by default for apps created after November 14, 2025.

For older apps, in the Clerk Dashboard, navigate to the Protect → Sign-in security page, select the settings icon in the Device Trust row, toggle on Enable, and select Save. Or set auth_password.device_trust.enabled with clerk config patch. Device Trust (first released as Client Trust) is included in all Clerk plans (changelog).

Neither the new-device email nor Device Trust has a dedicated webhook event, so handle session.created to alert your security team through your own channels, such as Slack or a security information and event management (SIEM) tool.

No-code option: Application Logs

In the Clerk Dashboard, the Logs page, which Clerk's docs call Application Logs, records session.created, session.ended, session.revoked, session.token.created, and session.reverification.* events, plus user.banned, user.locked, and user.deleted (session events, user events). Filter by Event type (trailing wildcards such as session.* work), Actor, Subject (for example, a user ID), IP address, or Device (filtering).

Application Logs are available on every plan and keep 1 day of history on Hobby, 7 days on Pro, 30 days on Business, and a custom period on Enterprise (plans and retention).

To investigate from a terminal, run clerk logs, which queries the same logs through the Backend API's GET /v1/logs endpoint. clerk logs --follow streams new events.

Clerk doesn't allow syncing or exporting logs through the Backend API (export logs), so stream session events to a SIEM with the webhook handler above. The Enterprise plan adds log sink destinations for a SIEM (pricing).

The Application Logs and webhook event lists differ. session.removed is webhook-only, and session.token.created, session.expiry.updated, and reverification events are log-only.

Session management tools compared: Clerk, WorkOS, Auth0, and Supabase

This table compares how each vendor lists, revokes, and monitors a user's sessions. Here, "session" means each vendor's user-facing sign-in session: the WorkOS AuthKit session, the Auth0 session layer, and the Supabase auth.sessions refresh-token session. The table doesn't cover SSO handshakes or agent sessions.

CapabilityClerkWorkOSAuth0Supabase
List a user's sessionsuser.getSessions() (frontend) and clerkClient.sessions.getSessionList({ userId }) (backend). Frontend, backendGET /user_management/users/{id}/sessions (listSessions). DocsGET /api/v2/users/{user_id}/sessions. API, how-toNot documented. The Sessions guide describes the auth.sessions table, keyed by the JSON Web Token (JWT) session_id claim. Docs
Revoke one sessionsession.revoke() for the user's own other sessions, and clerkClient.sessions.revokeSession(sessionId) from the backend. Frontend, backendPOST /user_management/sessions/revoke with a session_id (revokeSession). DocsDELETE /api/v2/sessions/{id}, or POST /api/v2/sessions/{id}/revoke to also revoke refresh tokens. Delete, revokesignOut({ scope: 'local' }) ends the current session. Revoking another session by ID: Not documented. Docs
Sign out everywhereList with getSessionList and revoke each, use setPasswordCompromised with revokeAllSessions, or ban with banUser(), which also blocks sign-in. Set compromised, banWidgets API revokeAllSessions (early access) revokes all but the current session. A password reset revokes all sessions, and membership deactivation revokes the user's sessions for that organization only. Otherwise, list the user's sessions and revoke each one. Widgets API, reset, membership, list, revokeDELETE /api/v2/users/{user_id}/sessions deletes all sessions asynchronously and is eventually consistent. A separate call revokes refresh tokens. API, how-tosignOut() defaults to the global scope in the JavaScript SDK and to local in Dart and Kotlin. { scope: 'others' } keeps the current session. Docs
Per-device metadataSessionActivity: browserName, browserVersion, deviceType, ipAddress, city, country, isMobile. Backend type, frontend typeip_address, user_agent, auth_method, and organization_id per session. The Widgets API adds city and country. Docs, Widgets APIdevice object with the initial and last user agent, IP address, and autonomous system number (ASN). session_metadata holds custom key-value data. DocsThe ip column in auth.sessions holds the session's IP address. Other device fields: Not documented. Audit log entries record ip_address only for some events, such as MFA and passkeys, and leave it empty for most sign-in, sign-out, and token events. Docs
Session events and webhookssession.created, session.ended, session.removed, and session.revoked webhook events. The Dashboard Event Catalog lists supported events. Event types, docssession.created and session.revoked events, by webhooks or the Events API. DocsNot documented as an event type. Nearest: Log Streams and back-channel logout initiators such as session-revoked. Events, Log Streams, initiatorsSession webhooks: Not documented. Auth audit logs record login, logout, and token_revoked. Docs
Reverification / step-upuseReverification() (client) and has({ reverification }) (server), with four preset levels or a custom window. Clerk-protected sensitive actions default to 10 minutes, configurable from 1 to 10. Docsauth_time claim plus a max_age authorization parameter, and checkRecentAuth() in the Next.js SDK. Docs, SDKThe app sends acr_values, an Action challenges for MFA, and the app checks amr. max_age with auth_time covers freshness. Step-up, max_agereauthenticate() covers password changes, and row-level security (RLS) policies can check aal2 and amr timestamps. Password, MFA
Prebuilt end-user session UI (embeddable component)<UserProfile /> Security page lists active devices with a per-device sign-out. Component, source, pricing<UserSessions /> widget lists active sessions and lets users sign out of individual sessions. DocsNot documented. Universal Components cover Organization admin, MFA factors, and passkeys. DocsNot documented. The Library's auth blocks are password, social, current-user avatar, and OAuth consent. Docs

"Not documented" means the vendor's public docs don't describe the behavior. Plan notes from each vendor's own pages:

  • Clerk: device tracking and revocation are included in every plan. MFA, which supplies reverification's second factor, needs a paid plan for production use (pricing). For log retention and the user ban plan note, see Application Logs and Part 1's offboarding section.
  • WorkOS: the pricing page and the docs linked above state no plan requirement for these features. The Widgets API launched in early access on July 3, 2026 (changelog).
  • Auth0: the session Management API endpoints in the first four rows and OpenID Connect (OIDC) Back-Channel Logout are on Enterprise plans. Log Streaming and MFA factors start at the Essentials plan (pricing).
  • Supabase: the pricing page lists Auth Audit Logs at 24 hours on Free, 7 days on Pro, and 28 days on Team. Supabase can also store audit events in the optional auth.audit_log_entries Postgres table (audit logs).

To put both parts to work, start with the active devices list from Part 1, then add the live session check to the route where a stale session would do the most damage.

In this series

  1. How to secure, monitor, and revoke user sessions with Clerk
  2. How to secure, monitor, and revoke user sessions with Clerk - Part 2 (you are here)