maxAge has passed and you would rather not stretch maxAge to weeks. Leave it off for kiosks, shared terminals and anything where a returning browser should always prove who it is again.
The feature is off unless you set auth.session.persistent. If you are adding it to a running app, start with upgrading to persistent sessions.
Enable it
lib/theauth.ts
openssl rand -base64 48), keep it in your secret store and give every instance the same value. The routes are served by createTheAuthHandler under its base path (/api/theauth by default), and migration 0016 adds the two tables at startup.
Startup checks
createTheAuth throws, usually with a message starting TheAuth: auth.session.persistent., when:
secretor an entry inpreviousSecretsis shorter than 32 bytes,idleTimeoutMsorabsoluteLifetimeMsis under 1000,idleTimeoutMsis not longer than the sessionmaxAge,graceMsis negative or over 300000,cookieNameis not a valid cookie name or equals the session cookie name,refreshRateLimitPerMinuteis not a positive integer.
maxAge defaults to 7 days. If yours is 30 days or more and you keep the default idleTimeoutMs, startup fails until you shorten maxAge or lengthen the idle timeout.
theauth doctor reports persistent.lifetime_long and persistent.idle_missing for lifetimes that boot but are looser than the defaults.
Ask to be remembered
A sign-in is remembered only when the request asks. The built-in routes read:- a
rememberfield in a JSON body or anapplication/x-www-form-urlencodedbody, withrememberMeaccepted as an alias, - or
?remember=1in the query string, which wins over the body.
1, true, on, yes, 0, false, off and no are understood. Anything else counts as not asked.
remember: true on the first step sets a signed intent cookie (theauth_remember_intent, Path set to the handler’s base path) that lasts 10 minutes and holds no credential. It is bound to that flow, so only a later step of the same flow picks it up. Starting another sign-in drops it, and an explicit false clears it.
Send
POST sign-ins as application/json. The handleRequest routes of the username, magic link, email code and phone modules ignore the choice on other content types, and so do magic link send requests. One Tap is the exception: it posts a form, which its handler checks with a double submit token.
Sign-in routes that answer in JSON
Some sign-in routes answer with the session token in JSON and set no session cookie: the username, magic link, email code and phonehandleRequest routes, and the magic link, email code, One Tap and native app exchange routes of the plugins. They still set the remember cookie, so you do not have to call persistentSessions.remember() for them. With no session cookie to protect these answers, theAuth checks where the request came from before it touches remember cookies:
A request that fails these rules can still sign in. It sets no remember cookie and leaves an existing one alone. The
handleRequest routes of modules do not receive trustedOrigins, so a frontend on another origin should call the routes served by createTheAuthHandler.
These are never remembered: anonymous sessions, impersonation sessions, device authorization sessions, and SAML sessions unless allowSaml is set. A pending second factor challenge is not a session, so nothing is created until it completes.
eligible runs when the device is created and can refuse it. If it throws, or the device cannot be stored, the sign-in still succeeds without a remember cookie.
Custom flows
For a flow of your own, or a client that keeps tokens itself, remember a session after you issue it.What the browser does
Both cookies areHttpOnly. The remember cookie is SameSite=Lax with Path=/, has an Expires date and no Domain, and is Secure except on plain-http loopback requests. A frontend on a different site than the auth routes will not send it on fetch calls.
When a request carries a remember cookie and has no valid session, the 401 includes the code session_expired. A client then:
- calls
POST /auth/session/refreshonce, with cookies, - retries the original request once if that returns 200,
- sends the user to sign-in if it returns 401 or 403 with a refresh code,
- keeps the user where they are on a network error, 429 or 5xx, and tries later.
@glinr/theauth-client and @glinr/theauth-react do this for you. If your own client redirects to sign-in on any 401, change that before you turn the feature on.
The refresh endpoint
POST /auth/session/refresh takes no body. It reads the remember cookie and, if present, the session cookie. It is the only route that rotates a token. No auth middleware ever does.
A success is 200:
rotated: false means the request already holds a live session, and no cookies change. Failures, status codes and which cookies are cleared are in the API reference.
Rotation, grace and reuse
Each refresh replaces the remember token and the session.- The previous token, presented within the grace window, returns the same successor. Tabs or instances that refresh at once end up with identical cookies. Nothing is stored in plain text to do this: the successor is derived from the secret and the presented token.
- If the previous token arrives after the grace window and nothing ever used the successor, theAuth assumes the response was lost and rotates once more.
- Any other old token counts as reuse. The device and its session are revoked,
onReuseruns, and an audit row with the actionsession.reuse_detectedis written when the agent tables exist.
Server-rendered pages
refreshFromRequest is the server side version, for a page gate that should not flash the sign-in screen. It returns the request’s live session, or refreshes from the remember cookie.
GET and HEAD it refuses to rotate when Sec-Fetch-Site says the navigation came from another origin. Other methods must pass the same origin check as the refresh route. Framework adapters wrap this as refreshPageSession. The result also has cookies, the same cookies parsed, and cookieHeader, the request’s Cookie header with them applied.
Call it only where Set-Cookie headers reach the browser. If a rendering layer drops them, the browser keeps the old token and can later trip reuse detection.
What a refreshed session is
It keeps the sign-in methods, the original authentication time and, ascreatedAt, the original sign-in time. It never counts as a fresh sign-in and carries no step-up elevation. Custom session metadata from the first session is not copied. It expires after the session maxAge, or at the device’s absolute deadline if that comes first. A refresh does not ask for a second factor again, and does not send new device or sign-in notices.
Manage devices
Each remembered sign-in is one device (a session family).GET /auth/session-families, PATCH and DELETE /auth/session-families/{id}, and POST /auth/session-families/{id}/forget. The list includes dormant devices whose session has expired but which can still refresh. Forgetting a device turns remember off and leaves its current session running until it ends. Another user’s device id answers 404.
What ends a device
- Sign-out, even when only the remember cookie is left.
- Revoking the device, or revoking a session or all of a user’s sessions through the session manager.
multiSession.revokeOtherSessionsalso ends devices that have no live session. - A new sign-in in the same browser. The earlier device ends, so one browser never holds two accounts’ devices.
- Password change and password reset, for every device including the current one. Users tick the box again at their next sign-in.
- Removing TOTP.
- Banning a user, requiring a password change, deleting or anonymizing the account (which also erases the device rows), SCIM deactivation or removal, and claiming a mailbox through a verified email sign-in.
- Session cap eviction. A refresh counts against
maxConcurrent: inrejectmode a refresh over the cap answersrefresh_deniedand keeps the device. Refreshed sessions keep the original sign-in time, so in evict-oldest mode remembered devices tend to be evicted first. checkreturning'revoke'.- Token reuse.
- The idle timeout or the absolute lifetime.
idleTimeoutMs ends the session, not the device: the next refresh mints a new session. Use persistent.idleTimeoutMs to limit how long a device stays remembered.
A refresh never switches accounts. When the request also holds a live session of another user, it answers remember_invalid and clears the remember cookie.
Policy hooks
limits runs at sign-in and on every refresh. It can only shorten: longer values are ignored, and a device keeps the shortest idle timeout and expiry it has received. A value shorter than the session maxAge is applied as given, so such a device can expire while its user is active.
check runs after the built-in user checks on every refresh that would hand out cookies. 'deny' refuses and keeps the device, 'revoke' ends it, and a thrown error refuses without revoking anything.
More than one instance
Instances agree on one rotation through a conditional database update, and derive the same cookies from the same secret. Changing the secret takes three deploys:- Add the new value to
previousSecretseverywhere. - Swap: new value in
secret, old one inpreviousSecrets. - Keep the old one for at least
idleTimeoutMsplus the sessionmaxAge, then remove it.
secret without keeping the old value in previousSecrets ends remembered devices at their next refresh. That is what you want if the secret leaked (also revoke the devices at once), and not otherwise.
Storage
Migration0016-persistent-sessions creates theauth_session_families and theauth_session_family_tokens on SQLite, Postgres and MySQL, and runs only when auth.session.persistent is set. Token verifiers are stored as SHA-256 hashes. Device rows also hold the user agent and client IP address.
On SQL Server, applyMssqlSchema creates the same tables. With Prisma, add the two models to your schema.
On Cloudflare D1, or with database.skipMigrations: true, apply it yourself: theauth db sql --dialect sqlite --from 0016.
Trade-offs
- A stolen token replayed within the grace window gets the same successor as the real client, and nothing flags it at that moment.
- The lost response rule allows exactly one extra rotation from the previous token after the grace window, if the successor was never used. A thief who replays that token before the real client returns gets one session. The real client’s next refresh then trips reuse detection and ends the device.
Example
examples/persistent-sessions runs the whole loop against an in-memory database: remember, lose the session, refresh, list devices and sign one out.