> ## Documentation Index
> Fetch the complete documentation index at: https://docs.theauth.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Persistent sessions

> Opt-in "keep me signed in" with a rotating remember cookie, reuse detection, device management and an explicit refresh endpoint.

Persistent sessions are the "keep me signed in" checkbox. A sign-in that asks for it gets a second, long-lived cookie next to the normal session cookie. When the session ends, the client trades that remember cookie for a new session and a new remember cookie.

Use it when people come back after your session `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](https://docs.theauth.dev/persistent-sessions-upgrade.md).

## Enable it

```typescript title="lib/theauth.ts" theme={"dark"}
import { createTheAuth } from '@glinr/theauth';

export const theauth = await createTheAuth({
  database: { provider: 'postgres', url: process.env.DATABASE_URL! },
  baseUrl: 'https://auth.example.com',
  emailPassword: { requireVerification: false },
  auth: {
    session: {
      secret: process.env.THEAUTH_SESSION_SECRET!,
      maxAge: 60 * 60 * 24, // seconds
      persistent: { // [!code highlight]
        secret: process.env.THEAUTH_REMEMBER_SECRET!, // [!code highlight]
      }, // [!code highlight]
    },
  },
});
```

Generate the remember secret once (`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.

| Option | Default | Meaning |
| - | - | - |
| `secret` | required | At least 32 bytes. Derives each rotated token. |
| `previousSecrets` | none | Older secrets, still accepted. Each at least 32 bytes. See [more than one instance](#more-than-one-instance). |
| `idleTimeoutMs` | 30 days | A device unused for this long ends. Must be longer than the session `maxAge`. |
| `absoluteLifetimeMs` | 90 days | A device ends this long after the original sign-in. Refreshing never moves it. |
| `graceMs` | 30 seconds | How long the previous token still returns the same successor. 0 to 300000. |
| `cookieName` | `theauth_remember` | Must differ from the session cookie name. |
| `refreshRateLimitPerMinute` | 60 | Refresh requests per minute per client IP. |
| `allowSaml` | `false` | Allow SAML sign-ins to be remembered. |
| `eligible` | none | Return `false` to refuse remember for a session. |
| `limits` | none | Shorten the two lifetimes per user. |
| `check` | none | Your own veto on each refresh. |
| `onReuse` | none | Called after a reused token ended a device. |

### Startup checks

`createTheAuth` throws, usually with a message starting `TheAuth: auth.session.persistent.`, when:

* `secret` or an entry in `previousSecrets` is shorter than 32 bytes,
* `idleTimeoutMs` or `absoluteLifetimeMs` is under 1000,
* `idleTimeoutMs` is not longer than the session `maxAge`,
* `graceMs` is negative or over 300000,
* `cookieName` is not a valid cookie name or equals the session cookie name,
* `refreshRateLimitPerMinute` is not a positive integer.

The idle timeout rule needs a word. A device is only seen when it refreshes, so a session that outlives the idle timeout would expire the device of someone who is still active. `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`](https://docs.theauth.dev/cli-tools) 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 `remember` field in a JSON body or an `application/x-www-form-urlencoded` body, with `rememberMe` accepted as an alias,
* or `?remember=1` in the query string, which wins over the body.

Booleans and the strings `1`, `true`, `on`, `yes`, `0`, `false`, `off` and `no` are understood. Anything else counts as not asked.

```typescript theme={"dark"}
await fetch('/api/theauth/auth/email/sign-in', {
  method: 'POST',
  credentials: 'include',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, password, remember: true }),
});
```

Some sign-ins take more than one request. There, `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.

| Sign-in path | Where to put the choice |
| - | - |
| Password sign-in and sign-up | The body of the sign-in or sign-up request. |
| Second factor or forced password change | The first password request. The intent cookie carries it to `/auth/sign-in/two-factor` or `/auth/sign-in/password-change`. |
| OAuth redirect | `?remember=1` on `/auth/oauth/authorize/{provider}`. |
| Magic link | The body of the send request. The user has to open the link in the same browser within 10 minutes. |
| Email code and phone code | The send request, or the verify request. |
| Passkey | The options request that starts authentication, or the verify request. |
| SAML | Needs `allowSaml`, and a session your code issues. See [custom flows](#custom-flows). |

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 phone `handleRequest` 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:

| Request | Honored when |
| - | - |
| `POST` | It is `application/json`. Any `Origin` or `Referer` it carries is your `baseUrl`, the request's own origin or one of the handler's `trustedOrigins`. Without either header, `Sec-Fetch-Site` is not `cross-site`, so clients that send none of these headers, such as native apps, pass. |
| `GET` | It carries a trusted `Origin` or `Referer`, or `Sec-Fetch-Site: same-origin`. |
| `GET` from anywhere else, such as a link opened from email | Only a choice the same browser made when it requested the link. A `remember` in the query string is ignored. |
| One Tap | Its handler checks a double submit token first. |

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.

```typescript theme={"dark"}
persistent: {
  secret: process.env.THEAUTH_REMEMBER_SECRET!,
  eligible: ({ userId, method }) => userId !== DEMO_USER_ID && method !== 'oauth',
},
```

### Custom flows

For a flow of your own, or a client that keeps tokens itself, remember a session after you issue it.

```typescript theme={"dark"}
const grant = await theauth.persistentSessions!.remember(sessionToken, {
  method: 'email_code',
  request,
});
if (grant.success) {
  headers.append('Set-Cookie', grant.data.setCookie); // browsers
  // native apps: store grant.data.rememberToken in the platform keychain
}
```

## What the browser does

Both cookies are `HttpOnly`. 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:

1. calls `POST /auth/session/refresh` once, with cookies,
2. retries the original request once if that returns 200,
3. sends the user to sign-in if it returns 401 or 403 with a refresh code,
4. keeps the user where they are on a network error, 429 or 5xx, and tries later.

[`@glinr/theauth-client` and `@glinr/theauth-react`](https://docs.theauth.dev/persistent-sessions-client) 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:

```json theme={"dark"}
{ "ok": true, "rotated": true, "sessionExpiresAt": "...", "rememberExpiresAt": "..." }
```

`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](https://docs.theauth.dev/persistent-sessions-api.md#refresh-route).

### 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, `onReuse` runs, and an audit row with the action `session.reuse_detected` is written when the agent tables exist.

A successor counts as used once a request authenticates with its session.

The idle timeout counts from the device's last rotation, or from the first request made with a refreshed session. Later requests on the same session do not extend it.

## 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.

```typescript theme={"dark"}
const result = await theauth.persistentSessions!.refreshFromRequest(request);
// Append these on success and on failure.
for (const cookie of result.setCookies) headers.append('Set-Cookie', cookie);

if (!result.success) {
  if (result.error.code === 'refresh_unavailable') return new Response('Try again', { status: 503 });
  return Response.redirect(new URL('/signin', request.url), 303);
}
renderFor(result.data.session);
```

On `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](https://docs.theauth.dev/persistent-sessions-adapters.md#page-gates) 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, as `createdAt`, 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).

```typescript theme={"dark"}
const devices = await theauth.persistentSessions!.list(userId, currentSessionId);
await theauth.persistentSessions!.rename(userId, devices[0].id, 'Work laptop');
await theauth.persistentSessions!.revoke(userId, devices[0].id);
```

The same operations are HTTP routes for the signed-in user: `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.revokeOtherSessions` also 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`: in `reject` mode a refresh over the cap answers `refresh_denied` and keeps the device. Refreshed sessions keep the original sign-in time, so in evict-oldest mode remembered devices tend to be evicted first.
* `check` returning `'revoke'`.
* Token reuse.
* The idle timeout or the absolute lifetime.

A session `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.

```typescript theme={"dark"}
persistent: {
  secret: process.env.THEAUTH_REMEMBER_SECRET!,
  limits: async ({ userId }) =>
    (await isAdmin(userId))
      ? { idleTimeoutMs: 8 * 86_400_000, absoluteLifetimeMs: 14 * 86_400_000 }
      : {},
  check: async ({ user }) => {
    const state = await accountState(user.id); // a throw answers refresh_unavailable
    if (state === 'paused') return 'deny';
    if (state === 'closed') return 'revoke';
    return 'allow';
  },
  onReuse: (device) => notifyUser(device.sessionId, device.deviceLabel),
},
```

`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:

1. Add the new value to `previousSecrets` everywhere.
2. Swap: new value in `secret`, old one in `previousSecrets`.
3. Keep the old one for at least `idleTimeoutMs` plus the session `maxAge`, then remove it.

Replacing `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

Migration `0016-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](https://docs.theauth.dev/persistent-sessions-adapters.md#prisma) 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.

See the [threat model](https://docs.theauth.dev/persistent-sessions-threat-model.md) for the full list.

## Example

[`examples/persistent-sessions`](https://github.com/glincker/theauth/tree/main/examples/persistent-sessions) runs the whole loop against an in-memory database: remember, lose the session, refresh, list devices and sign one out.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.