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

> Configuration types, the theauth.persistentSessions methods, HTTP routes, status codes and cookies of persistent sessions.

Reference for [persistent sessions](https://docs.theauth.dev/persistent-sessions.md). All types are exported from `@glinr/theauth`.

## theauth.persistentSessions

`null` unless `auth.session.persistent` is set. Methods that take a `userId` act only on that user's devices.

| Method | Returns | Notes |
| - | - | - |
| `refresh(input)` | `Result<PersistentRefreshOutcome>` | Trades a remember token for a session. For browsers prefer the HTTP route, which sets cookies and checks the origin. |
| `refreshFromRequest(request, options?)` | `RequestRefresh` | The request's live session, or a refresh from its cookies. `options.trustedOrigins` extends the origin check. |
| `list(userId, currentSessionId?)` | `SessionFamilyView[]` | Newest first, dormant devices included. |
| `rename(userId, familyId, label)` | `Result<{ familyId }>` | Label up to 100 bytes. Errors: `invalid_body`, `not_found`. |
| `revoke(userId, familyId)` | `Result<{ sessionId }>` | Ends the device and its session. Error: `not_found`. |
| `revokeOthers(userId, keepSessionId)` | `number` | Ends every device except the one holding that session. |
| `revokeAll(userId)` | `number` | Ends every device of the user. |
| `revokeBySession(sessionId)` | `void` | Ends the device behind a session. It takes no user id, so check permission yourself. |
| `forget(userId, familyId)` | `Result<{ sessionId }>` | Turns remember off. The current session keeps working until it ends. |
| `remember(sessionToken, options?)` | `Result<RememberGrant>` | Remembers a session you issued. Errors: `invalid_session`, `not_eligible`, `remember_unavailable`. |

### refresh

```typescript theme={"dark"}
const result = await theauth.persistentSessions!.refresh({
  rememberToken,
  sessionToken, // optional: a live session of the same device makes this a no-op
  userAgent,
  ip,
});

if (result.success && result.data.rotated) {
  save(result.data.sessionToken, result.data.rememberToken);
}
```

`PersistentRefreshOutcome` has `rotated`, `session`, `sessionToken`, `rememberToken`, `rememberExpiresAt` and `family`. With `rotated: false`, both tokens are `null` and you keep the ones you have. Failures carry one of the [refresh error codes](#error-codes).

Replace both stored tokens before you use either of them. A client that keeps an old remember token will trip reuse detection.

### RequestRefresh

`Result<{ session, rotated }>` plus:

| Field | Meaning |
| - | - |
| `setCookies` | `Set-Cookie` values. Append every one to the response, on failure too. |
| `cookies` | The same cookies parsed into name, value and attributes, for framework cookie APIs. |
| `cookieHeader` | The request's `Cookie` header with those cookies applied, for code that runs later in the same request. |

`refreshFromRequest` reads headers only, so a request body stays unread. `toWebRequest` from `@glinr/theauth/http` takes `skipBody` for the same reason.

### RememberOptions

| Field | Meaning |
| - | - |
| `method` | Recorded on the device. Derived from the session's authentication methods when unset. |
| `request` | Supplies the user agent, client IP and the cookie `Secure` decision. |
| `userAgent`, `ip` | Used instead of the request's values. |

`RememberGrant` has `rememberToken`, `rememberExpiresAt` and `setCookie`.

`RememberMethod` is one of `password`, `signup`, `mfa`, `passkey`, `magic_link`, `email_code`, `oauth`, `saml`, `phone` or `programmatic`.

## SessionFamilyView

| Field | Meaning |
| - | - |
| `id` | Device id, used by the management calls. |
| `sessionId` | Session of the current generation. It may have expired. |
| `live` | That session can still authenticate. |
| `persistent` | `false` once the device was forgotten. |
| `current` | The caller's own device. |
| `method`, `label` | Sign-in method and the user's own name for the device. |
| `deviceLabel` | A short "Browser on OS" text from the user agent. |
| `userAgent` | As sent at sign-in or the last refresh. |
| `ipPrefix` | The address masked to /24 (IPv4) or /48 (IPv6). |
| `signedInAt`, `lastUsedAt` | Original sign-in and last activity. |
| `idleDeadline`, `absoluteDeadline` | When the device ends if unused, and regardless. |

## Hooks

| Hook | Input | Result |
| - | - | - |
| `eligible` | `{ userId, session, method }` | `false` refuses remember. A throw refuses. |
| `limits` | `{ userId, method }` | `{ idleTimeoutMs?, absoluteLifetimeMs? }`, which can only shorten. |
| `check` | `{ user: { id, email, name }, family }` | `'allow'`, `'deny'` or `'revoke'`. A throw refuses without revoking. |
| `onReuse` | `SessionFamilyView` | Runs after the device was revoked. Errors are logged. |

All four may be async.

## HTTP routes

Paths are relative to the handler's base path, `/api/theauth` by default. Responses carry `Cache-Control: no-store` unless noted.

### Refresh route

`POST /auth/session/refresh`, no body.

Checks, in order:

* **Origin.** `Origin`, or `Referer` without it, must match `baseUrl`, the request's own origin or the handler's `trustedOrigins`. With neither header, `Sec-Fetch-Site: same-origin` is required. A remember cookie alone can mint a session, so this check is separate from the general cross-site one.
* **Transport.** With an `https` `baseUrl`, plain http requests are refused. Behind a TLS terminating proxy, set `trustedProxy` so its forwarded protocol counts.
* **Rate limit.** `refreshRateLimitPerMinute` per client IP.

Success:

```json theme={"dark"}
{
  "ok": true,
  "rotated": true,
  "sessionExpiresAt": "2026-01-02T10:00:00.000Z",
  "rememberExpiresAt": "2026-02-01T09:00:00.000Z"
}
```

Failures have the shape `{ "error": { "code", "message" } }`.

### Error codes

| Status | Code | What happened | Cookies |
| - | - | - | - |
| 401 | `remember_invalid` | No token, an unknown one, or a device that ended, was forgotten or saw a password or second factor change. | Remember cookie cleared. |
| 401 | `remember_expired` | Idle timeout or absolute lifetime passed. | Remember cookie cleared. |
| 401 | `remember_reused` | An old token came back, and the device was ended. | Both cleared. |
| 403 | `refresh_denied` | The user is gone, banned or has to change the password (this ends the device), `check` said no, or the session cap refused. | Kept. |
| 503 | `refresh_unavailable` | A temporary failure. Nothing was revoked. `Retry-After: 1`. | Kept. |
| 403 | `csrf_origin_rejected` | Origin check failed. | Kept. |
| 403 | `insecure_transport` | Plain http with an `https` base URL. | Kept. |
| 429 | `rate_limited` | Too many refreshes. `Retry-After: 60`. | Kept. |

### Device routes

All need a valid session. Without one they answer 401 with `session_expired` when a remember cookie is present, otherwise `unauthorized`.

| Route | Body | Success |
| - | - | - |
| `GET /auth/session-families` | none | 200 `{ "devices": SessionFamilyView[] }`, dates as ISO strings. |
| `PATCH /auth/session-families/{id}` | `{ "label": "Work laptop" }` | 204 |
| `DELETE /auth/session-families/{id}` | none | 204. Clears both cookies when it is the current device. |
| `POST /auth/session-families/{id}/forget` | none | 204. Clears the remember cookie when it is the current device. |

An unknown id, or one of another user, answers 404 `not_found`.

### Changes to existing routes

While persistent sessions are on:

* `GET /auth/session` answers `{ "error": "Not authenticated", "code": "session_expired" }` when a remember cookie is present and no session is valid.
* Plugin routes that require a session add `"code": "session_expired"` to their 401 under the same condition.
* `POST /auth/sign-out` also ends the device named by the remember cookie, clears it, and answers 200 even if the session had already ended. If the device cannot be ended it answers 500 and the user should retry.
* `POST /auth/2fa/disable` ends the user's remembered devices when it succeeds.
* Sign-in routes read `remember` and may set the remember and intent cookies.

## Cookies

| Cookie | Default name | Attributes | Lifetime |
| - | - | - | - |
| Remember | `theauth_remember` | `HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure` except on plain-http loopback | `Expires` at the idle deadline of the current token, never past the absolute deadline |
| Intent | `theauth_remember_intent` | Same, with `Path` set to the base path | 10 minutes |

The remember cookie value is `<device id>.<verifier>`. Do not parse it and do not log it.


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