Skip to main content
theAuth has three session types:
  • Cookie sessions for human users in browsers. A signed JWT sits in an httpOnly cookie. The session record lives in your database so you can revoke it instantly.
  • JWT sessions for SPAs, mobile apps, and server-to-server flows. Stateless access tokens paired with rotating refresh tokens.
  • Ephemeral agent sessions for AI agents (Claude, GPT-with-browsing, operator loops). Short-lived, budget-bounded credentials that expire by time or action count, whichever comes first.
This page covers cookie sessions and JWT sessions. For ephemeral agent sessions see the agents guide.
1

Configure the session manager

Pass createCookieSessionManager a config object and your theauth.db instance. The manager handles creation, validation, refresh, and revocation.
lib/theauth.ts
2

Create a session after sign-in

Call createSession with a user ID after your authentication logic succeeds. createSession returns the session record and a ready-made Set-Cookie header value to send back to the browser. It does not return a Result: it resolves with the data or throws.
routes/sign-in.ts
3

Validate on each request

Pass the raw Cookie request header to validateSession. It returns { session, refreshCookieHeader }. session is null when the cookie is missing, invalid, expired, or revoked.
middleware.ts
When autoRefresh is on (the default), every successful validateSession call extends the session. Internally the old session row is deleted and a new one is created, so the session ID changes on each refresh. validateSession returns the new cookie as refreshCookieHeader. Forward it in your response.
middleware.ts
4

Revoke on sign-out

Revoking a session removes it from the database immediately. Any subsequent validation attempt returns session: null.
routes/sign-out.ts

Idle timeout and remember me

Both are opt-in. With neither set, sessions behave exactly as before.
Idle timeout. idleTimeoutMs denies a session with no activity for that long, in addition to the absolute maxAge, which still applies. It is off by default: turning it on signs users out and adds a small write to busy sessions, so it is your call. Activity is recorded in lastActiveAt, written at most once per activityGranularityMs (default 60 seconds, or a quarter of the idle timeout when that is shorter), so a busy session costs one write per window and the effective idle limit can be up to one window longer than configured. activityGranularityMs must be shorter than idleTimeoutMs. Sessions created before you enabled the feature have no stamp and are treated as active on first read, not logged out. An idle session is deleted (and onRevoke is called), so it cannot return. validateSession still answers session: null; read reason for idle_timeout, expired, not_found or invalid_token. With the raw manager use validateDetailed(token). Environment overrides, used when the option is not set in code: THEAUTH_SESSION_IDLE_TIMEOUT_MS, THEAUTH_SESSION_ACTIVITY_GRANULARITY_MS, THEAUTH_SESSION_REMEMBER_ME_MAX_AGE. Remember me. rememberMe: true uses rememberMeMaxAge (default 30 days) as the absolute lifetime, never more than rememberMeMaxAgeCap (default 90 days). rememberMe: false keeps the normal lifetime and, through the cookie manager or buildSessionCookie(name, token, session), sends a cookie with no Max-Age, so the browser drops it on close. Leaving it unset keeps the old behavior (persistent cookie for maxAge). The choice is kept when a session is refreshed. If you build the cookie yourself from createTheAuth sessions, use buildSessionCookie so rememberMe: false is honored. Remember me on the sign in routes. The built in sign in paths accept an optional rememberMe choice and pass it to create. Username sign in reads rememberMe (boolean) from the JSON body. Passkey verify (/auth/passkey/authenticate/verify) and the two-factor and password-change completions of the sign in gate read it from the JSON body too. The magic link verify route reads ?rememberMe=true|false, and /auth/oauth/authorize/:provider reads the same query parameter and carries it to the callback in a short lived cookie. Routes that set the session cookie (passkey, OAuth callback, gate completions) send a browser session cookie for false and a persistent cookie until expiresAt for true. The username and magic link modules return JSON, so they report the choice as session.rememberMe for the code that sets your cookie. A value that is not a boolean counts as absent, and with no choice every route keeps the old persistent cookie and the normal lifetime. true never exceeds rememberMeMaxAgeCap. Email OTP, phone, one tap and anonymous sign in do not read the option yet. The activity stamp and the remember me flag live in the session metadata JSON (no schema change). They are hidden from session.metadata and exposed as session.lastActiveAt and session.rememberMe. The stamp write re-reads the row first, but a metadata write landing in the same few milliseconds can still be overwritten by it, and the next activity repairs the stamp.

JWT sessions

Use JWT sessions when cookies don’t work: SPAs calling a separate API origin, mobile apps, server-to-server flows. Access tokens are short-lived and stateless. Refresh tokens are opaque random strings stored as SHA-256 hashes, and they rotate on every use.
lib/theauth.ts
customClaims receives only { id, email?, name? }. On refresh the module re-issues tokens from { id } alone, so claims that depend on email or name are not present on tokens minted by refreshSession.

Create a session

routes/sign-in.ts

Verify on each request

Access token verification is stateless. No database round-trip.
middleware.ts

Refresh

Calling refreshSession marks the old refresh token as used and issues a new access + refresh pair. Each refresh rotates the token, so a stolen token is invalidated the moment the legitimate client refreshes.
routes/refresh.ts
If refreshSession returns REFRESH_TOKEN_USED, a previously-used token was replayed. This is a strong signal that the refresh token was stolen. The module only rejects the replayed token: it does not revoke the newer token it issued. Revoke the user’s other refresh tokens with revokeSession and force re-authentication.

Session freshness

Some operations should require that the user authenticated recently, not just that they hold any valid session. Changing a password, registering a passkey, or modifying billing details are examples where a session from 6 days ago is not good enough even though it is technically valid. createSessionFreshnessModule wraps this check. When a session is older than freshAge seconds, it returns a 403 response with code SESSION_NOT_FRESH. Your handler returns it directly.
lib/freshness.ts
Use it in any endpoint that needs re-authentication assurance:
routes/change-password.ts
When the client receives SESSION_NOT_FRESH, redirect them to a lightweight re-authentication page (password confirmation, passkey prompt, or similar) rather than a full sign-out. After re-auth succeeds, refresh the session’s createdAt timestamp by issuing a new session, then retry the original operation.
The freshAge threshold is separate from maxAge. A session can be well within its 7-day lifetime but still be considered stale for sensitive operations. Keep freshAge short. 5 to 15 minutes is typical.

CSRF protection

Cookie-based sessions are vulnerable to cross-site request forgery unless you add a second layer. theAuth uses the double-submit cookie pattern: a random token is set in a separate readable cookie and must also appear in the request body or header. An attacker’s page can trigger the cookie but cannot read it to reproduce the header value.
lib/csrf.ts
The CSRF cookie must not be httpOnly. It needs to be readable by JavaScript so the client can include its value in the x-csrf-token request header. Set it as SameSite=Strict instead.

Revocation patterns

Revoke one session

Session metadata

Store arbitrary data on a session at creation time. Useful for tracking the device, IP address, or a custom attribute your app needs. The object you pass as the second argument of createSession is stored as the session metadata. There is no separate call to update it later.
Creating a session with metadata
Read it back when you validate:
Reading session metadata
Metadata is stored as a JSON column. It is not indexed, so avoid querying sessions by metadata fields. If you need to look up sessions by device or IP, store those in a separate indexed column via a custom schema extension.

Human sessions vs agent tokens

Agent tokens use a ta_ prefix and are stored only as a SHA-256 hash. The raw token is shown once at creation and cannot be recovered. If a token is lost, issue a new one.

Error codes

The cookie session manager does not return error codes: validateSession returns session: null for a missing, invalid, expired, or revoked cookie. The JWT session module and the helpers return the following: validateCsrfToken and validateOrigin return { valid: false, reason } rather than a code. The status codes in the table are what the modules suggest, not something the library sets on a response (except the 403 from freshness.guard).

Configuration reference

CookieSessionConfig

string
required
Signing secret for the session token, at least 32 characters.
string
default:"'theauth_session'"
Name of the session cookie.
number
default:"604800 (7 days)"
Session lifetime in seconds. After this period the session is considered expired even if it has been used recently.
boolean
default:"true"
When true, every successful validateSession extends the session by replacing the session row (the session ID changes) and returns a new cookie as refreshCookieHeader.
number
default:"off"
Deny a session with no activity for this many ms. Env THEAUTH_SESSION_IDLE_TIMEOUT_MS.
number
default:"60000 (or idleTimeoutMs / 4 if shorter)"
Minimum age of lastActiveAt before it is rewritten. Must be below idleTimeoutMs. Env THEAUTH_SESSION_ACTIVITY_GRANULARITY_MS.
number
default:"2592000 (30 days)"
Absolute lifetime in seconds for rememberMe: true. Env THEAUTH_SESSION_REMEMBER_ME_MAX_AGE.
number
default:"7776000 (90 days)"
Hard ceiling on the remember me lifetime.
Prevents client-side JavaScript from accessing the cookie. Always set this to true for session cookies.
Only send the cookie over HTTPS. Set it to true explicitly if your deployment does not set NODE_ENV=production.
Controls cross-site cookie behavior. ‘lax’ works for most apps. ‘strict’ adds more protection. ‘none’ is only for cross-origin cookie transport (requires secure: true).
Restricts the cookie to a URL path prefix.
Set a cookie domain to share sessions across subdomains. Omit for single-domain apps.

JwtSessionConfig

string | CryptoKey | JsonWebKey
required
Signing secret. A string uses HMAC-SHA256 and must be at least 32 characters. Pass a CryptoKey or JsonWebKey for asymmetric algorithms (RS256, ES256).
string
default:"'HS256'"
JWT signing algorithm. Inferred from the secret type when not set: ‘HS256’ for strings, ‘RS256’ for RSA keys, ‘ES256’ for EC keys.
number
default:"900 (15 min)"
Access token lifetime in seconds. Keep this short. Access tokens are stateless and cannot be revoked before expiry.
number
default:"604800 (7 days)"
Refresh token lifetime in seconds. Refresh tokens are stored hashed and can be revoked immediately.
string
default:"undefined"
Value for the JWT ‘iss’ claim. Validated on every verify call.
string
default:"undefined"
Value for the JWT ‘aud’ claim. Validated on every verify call.
(user: { id: string; email?: string; name?: string }) => Record<string, unknown>
default:"undefined"
Function called at token creation to attach extra claims to the access token payload.

SessionFreshnessConfig

number
default:"300 (5 min)"
Maximum session age in seconds before a sensitive operation requires re-authentication. The freshness guard returns 403 SESSION_NOT_FRESH when the session is older than this.

Security best practices

Always keep cookieOptions.httpOnly: true and set cookieOptions.secure: true in production. Without httpOnly, a single XSS vulnerability lets an attacker read the session cookie directly. Without secure, the cookie travels over plain HTTP and can be intercepted on any network path.
Rotate the session secret periodically. All existing sessions signed with the old secret become invalid when you rotate. Plan for a brief period where some users need to sign in again, or run with two active secrets during the transition window.
Set cookieOptions.sameSite: 'lax' for most apps. 'lax' allows the cookie to be sent on top-level navigations (clicking a link) but blocks it on cross-origin subresource requests, which stops most CSRF attacks without breaking OAuth redirect flows. Only use 'strict' if you have no external links that expect to land in an authenticated state.
Short access token TTLs (accessTokenTtl) reduce the window of exposure for a stolen token, but they increase refresh traffic. 15 minutes is a reasonable default. If you need to revoke access instantly (account ban, credential compromise), route your API through the session validation middleware instead of relying solely on stateless JWT verification.

Cookie options

Cookie attributes, cross-subdomain setup, and rolling vs absolute expiry.

JWT sessions

Stateless access tokens with rotating refresh tokens.

Multi-session

Cap concurrent sessions and build an active devices settings page.

Ephemeral sessions

Short-lived, budget-bounded agent credentials for single tasks.
Last modified on October 18, 2026