
# Read, update and clear

> Open the session of a request, sign a visitor in, change what the session holds, sign them out, and mint or open tokens without a request.

Every request starts with `use(event)`: it reads the token the request carries and gives you the session, a small object with the visitor's `data` and two actions, `update()` and `clear()`. The examples on this page run in any handler that receives a `Request` and returns a `Response`, such as Cloudflare Workers, Bun, Deno or Hono, and they use the `appSession` definition from [Configure a session](/sessions/configure). For h3, Nitro and Nuxt, their event goes to `use()` as it is: [Sessions](/sessions#pick-your-framework) points to each recipe.

## Before you start

- A session definition, made once at start-up, as in [Configure a session](/sessions/configure).
- Pass `use()` the request you are handling, never an object you keep between requests. The session of a request is remembered on that request, so a second `use()` in the same request returns the same session.
- One name is one cookie. Two definitions of the same kind with the same `name` share one session on a request, and a JWS and a JWE definition under one name on the same request throw `ERR_SESSION_CONFIG_INVALID`.
- Update or clear the session before you build the `Response`. `new Response(body, { headers })` copies the headers when it is created, so a cookie written afterwards never reaches the client, and nothing tells you so.

## What `use()` takes

| You pass                                | The session reads                                            | `update()` and `clear()` on a cookie session     |
| --------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------ |
| `{ req, res: { headers } }`             | the cookie of `req`, or the session header when you name one | write `Set-Cookie` lines onto `headers`          |
| a `Request`, `{ req }` or `{ headers }` | the same                                                     | `update()` throws, `clear()` empties the session |
| `{ token }`                             | that token                                                   | not a cookie session: see below                  |

`req` is the incoming `Request`, and `headers` is the `Headers` you send the response with. Any other object throws `ERR_SESSION_INVALID`.

## Where the token came from

`session.source` says where this request's token comes from, and it decides what `update()` and `clear()` reach. It is picked before the token is opened and holds for the whole request:

| `session.source` | The token came from                                                               | `update()`                                  | `clear()`                                                        |
| ---------------- | --------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------- |
| `"cookie"`       | the cookie, also when the session header holds the same token                     | writes the new token to the cookie          | expires the cookie                                               |
| `"header"`       | the session header, when the request sends no cookie or one holding another token | puts the new token on `session.token` alone | empties the session for this request; the client keeps its token |
| `"token"`        | the token you passed as `use({ token })`                                          | puts the new token on `session.token` alone | empties the session for this request; the client keeps its token |

A header or token session writes nothing to the response and never rolls: a new token reaches the client only if you send it, as [Sessions without cookies](/sessions/api-clients) does. [Configure a session](/sessions/configure#accept-the-token-in-a-header) has the rule for a request that sends both a header and a cookie.

## Sign a visitor in

After your own check of the credentials, write the visitor into the session:

<!-- automd:region src="../../examples/sessions/handlers.ts" name="sign-in" -->

```ts [handlers.ts]
/** Call once your own credential check has passed. */
export async function signIn(req: Request, user: { id: string; role: "member" | "admin" }) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  await session.update({ userId: user.id, role: user.role });
  return Response.json({ expiresAt: session.expiresAt }, { headers });
}
```

<!-- /automd -->

- **No session yet**: before `update()`, `session.id` is `undefined` and `session.token` too. Calling `use()` alone sets no cookie, so visitors who never sign in never get one.
- **`update()`**: merges the object into `session.data`, issues a new token with a fresh `id`, and adds its `Set-Cookie` line to `headers`.
- **Reserved names**: `jti`, `iat`, `exp` and `nbf` are the session's own claims. They are dropped from what you pass and never appear in `session.data`.

## Read the session

A request that carries a valid token gets its data back. One without a token, or with a token that is expired, tampered with or not a session at all, gets an empty session:

<!-- automd:region src="../../examples/sessions/handlers.ts" name="profile" -->

```ts [handlers.ts]
export async function profile(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (!session.id) return new Response("Sign in first", { status: 401, headers });
  return Response.json(session.data, { headers });
}
```

<!-- /automd -->

`if (!session.id)` is the check for "signed in". The response passes `headers` on even here, because `rolling` may replace the token as it is read, and a token that fails its checks has its cookie expired. The session has these members:

| Member      | Holds                                                                                                                        |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `id`        | The token's ID (`jti`), or `undefined` without a session. Changes with every `update()`.                                     |
| `data`      | Your data, typed by the definition. `{}` without a session.                                                                  |
| `createdAt` | When the current token was issued, in milliseconds.                                                                          |
| `expiresAt` | When it expires, in milliseconds: its `exp`, or issue time plus `maxAge` if that is sooner.                                  |
| `token`     | The token behind `data`: read and opened, or issued by `update()`. `undefined` after a failed read.                          |
| `source`    | `"cookie"`, `"header"` or `"token"`: where the token of this request comes from.                                             |
| `error`     | The `JWTError` the read ended with, or `undefined`: see [Tell what happened to the token](#tell-what-happened-to-the-token). |
| `update()`  | Merges data, issues a new token, writes the cookie on a cookie session. Resolves to the same session.                        |
| `clear()`   | Empties the session and expires the cookie on a cookie session. Resolves to the same session.                                |

Data travels as JSON: the request that writes it keeps the values you gave, and later requests get them back the way `JSON.parse` would. A `Date` comes back as a string.

## Change the session

`update()` with an object changes only the keys you name:

<!-- automd:region src="../../examples/sessions/handlers.ts" name="switch-workspace" -->

```ts [handlers.ts]
export async function switchWorkspace(req: Request, workspaceId: string) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (!session.id) return new Response("Sign in first", { status: 401, headers });
  await session.update({ workspaceId });
  return new Response(null, { status: 204, headers });
}
```

<!-- /automd -->

`update()` also takes a function of the current data. It returns the keys to change, or changes the data in place and returns nothing. `undefined` with no change keeps the data as it is. A second argument gives this one token its own lifetime:

```ts
await session.update((data) => (data.role === "member" ? { role: "admin" } : undefined));
await session.update((data) => {
  delete data.workspaceId; // in place, returns nothing
});
await session.update(undefined, { maxAge: "15m" }); // a new token, same data, 15 minutes
```

`update()` with no arguments issues a new token with a new ID and a fresh expiry, and keeps the data. A token issued earlier keeps working until it expires. A longer `maxAge` than the config's still ends at the config's `maxAge` when the token is read back.

Await each `update()` and `clear()` before the next one. Calls that overlap on one session run in no set order, and the last cookie write wins.

## Sign a visitor out

<!-- automd:region src="../../examples/sessions/handlers.ts" name="sign-out" -->

```ts [handlers.ts]
export async function signOut(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  await session.clear();
  return new Response(null, { status: 204, headers });
}
```

<!-- /automd -->

`clear()` leaves an empty session for the rest of the request and writes a `Set-Cookie` line with `Max-Age=0` for the cookie, and for every part of a split one. It works when the request carried no session too.

## What the response carries

| You did                                   | `headers` gets                                         |
| ----------------------------------------- | ------------------------------------------------------ |
| `use()` only, on a valid token            | nothing, unless `rolling` replaced the token           |
| `use()` on a cookie that fails its checks | a `Max-Age=0` line that removes it                     |
| `use()` when `onKeyLookup` fails          | nothing: the cookie is kept                            |
| `update()`                                | the new cookie; a second `update()` replaces that line |
| `clear()`                                 | a `Max-Age=0` line, replacing any line written earlier |
| anything, on a header or token session    | nothing: the new token is on `session.token`           |

Other `Set-Cookie` lines in `headers`, such as a theme cookie, are kept.

## Read without a response

A `Request` on its own reads the session and writes nothing. It suits a check that never changes the session, such as a WebSocket upgrade or a server-rendered page that only shows the user's name:

```ts
const session = await appSession.use(req);
session.data.userId; // "user_1a2b"
await session.update({ role: "admin" }); // throws ERR_SESSION_READONLY_EVENT
```

`clear()` on such a session empties it for the rest of the request and resolves; the cookie stays with the client until a request with a response clears it. An expired or unreadable token still reaches its [hooks](/sessions/hooks), and `rolling` waits for the next request.

The read-only case is a cookie session's: it has a cookie to write and no response to write it to. A session header that holds the same token as the cookie still makes the request a cookie session, so `update()` throws there too. A request whose header holds another token, or that sends no cookie, is a header session, and `update()` puts the new token on `session.token`.

## Use a token you hold

Some clients keep the token themselves and send it inside a message, such as a desktop app talking JSON or a job in a queue. Hand that token to `use()`:

<!-- automd:region src="../../examples/sessions/handlers.ts" name="token-in-hand" -->

```ts [handlers.ts]
/** A desktop client keeps its token itself and sends it in each message. */
export async function renew(message: { session: string }) {
  const session = await appSession.use({ token: message.session });
  if (!session.id) return { session: null };
  await session.update();
  return { session: session.token ?? null };
}
```

<!-- /automd -->

The token goes through the same checks and hooks as a cookie, and `session.source` is `"token"`. `update()` puts the new token on `session.token` and writes nothing; `clear()` leaves `session.token` `undefined`. `rolling` never reissues it. The config's `cookie` and `sessionHeader` play no part, and `use({ token: undefined })` is an empty session.

## Issue and open tokens without a request

`issue(data)` mints a token with a fresh ID and the definition's `maxAge`, and `open(token)` reads one back with the same checks as a cookie. Neither needs a request, which makes them the pair for magic links, email confirmations and API tokens:

<!-- automd:region src="../../examples/sessions/magic-link.ts" -->

```ts [magic-link.ts]
import { isJWTError } from "unjwt/error";
import { defineJWESession } from "unjwt/session";
import { appSession } from "./app-session.ts";

// const linkKey = a second "oct" JWK, loaded like SESSION_KEY

const magicLink = defineJWESession<{ email: string }, "15m">({
  key: linkKey,
  maxAge: "15m",
  cookie: false,
  sessionHeader: false,
});

/** The link to email; it signs in whoever opens it within 15 minutes. */
export async function magicLinkFor(email: string) {
  const url = new URL("https://app.example.com/auth/callback");
  url.searchParams.set("token", await magicLink.issue({ email }));
  return url;
}

/** `GET /auth/callback?token=…`: opens the link token, then starts the app session. */
export async function redeemMagicLink(req: Request) {
  const token = new URL(req.url).searchParams.get("token");
  if (!token) return new Response("Missing token", { status: 400 });

  let email: string;
  try {
    ({ email } = (await magicLink.open(token)).data);
  } catch (error) {
    if (isJWTError(error)) return new Response("This link is invalid or expired", { status: 401 });
    throw error;
  }

  const user = await findUserByEmail(email);
  const headers = new Headers({ location: "/" });
  const session = await appSession.use({ req, res: { headers } });
  await session.update({ userId: user.id, role: user.role });
  return new Response(null, { status: 303, headers });
}
```

<!-- /automd -->

- **A definition of its own**: `cookie: false` and `sessionHeader: false` mean no request can carry this token by accident: `use()` on a request throws `ERR_SESSION_CONFIG_INVALID`, while `use({ token })` works.
- **Its own key**: the link token cannot be replayed as the app's session cookie, because the app session cannot open it.
- **Failures throw**: `open()` has no hooks to report to, so an expired token throws `ERR_JWT_EXPIRED`, and a tampered or foreign one `ERR_SESSION_TOKEN_INVALID`. With [`onKeyLookup`](/sessions/hooks#rotate-with-onkeylookup) set, a lookup that fails throws `ERR_SESSION_READ_FAILED`. All are `JWTError`s.
- **What `open()` returns**: `{ id, createdAt, expiresAt, data, source }`, with `source` always `"token"`. `issue()` takes `{ maxAge }` as a second argument, like `update()`.

## Read the raw token

`token(event)` returns the token a request carries, unopened and unchecked, from the source that request runs on: a token in hand, the session header for a header session, else the cookie. What `use()` makes of it doesn't change it: a token that fails its checks, or whose read fails, is returned as it was sent. After `update()` it returns the new token, after `clear()` `undefined`. A header that holds no token, such as `Basic …`, gives `undefined` too.

### Two views of the token

|                     | `token(event)`                                  | `session.token`                 |
| ------------------- | ----------------------------------------------- | ------------------------------- |
| Holds               | the token the request carries, or the new token | the token behind `session.data` |
| After a failed read | the token as it was sent                        | `undefined`                     |
| After `update()`    | the new token                                   | the new token                   |
| After `clear()`     | `undefined`                                     | `undefined`                     |

- **`token(event)`**: forward or log the token a request carried, or tell a request without a token, `undefined`, from one whose token could not be checked, a token while `session.id` is `undefined`.
- **`session.token`**: hand a client its new token after `update()`, as [Use a token you hold](#use-a-token-you-hold) does.

## Tell what happened to the token

`session.error` is the `JWTError` the read ended with, the same object `onExpire` or `onError` received, so a handler can answer each outcome without a hook. This one runs on the `appSession` of [Rotate with onKeyLookup](/sessions/hooks#rotate-with-onkeylookup), whose keys come from a secret manager, so a read can fail even with a good token:

<!-- automd:region src="../../examples/sessions/read-outcome.ts" -->

```ts [read-outcome.ts]
import { appSession } from "./key-lookup.ts";

/** `GET /dashboard`: the visitor's data, a guest view, or why there is neither. */
export async function dashboard(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (session.id) return Response.json({ userId: session.data.userId }, { headers });

  switch (session.error?.code) {
    case undefined:
      return Response.json({ guest: true }, { headers });
    case "ERR_SESSION_READ_FAILED":
      headers.set("retry-after", "5");
      return new Response("Sign-in is unavailable, try again shortly", { status: 503, headers });
    case "ERR_JWT_EXPIRED":
      return new Response("Your session expired, sign in again", { status: 401, headers });
    default:
      return new Response("Sign in again", { status: 401, headers });
  }
}
```

<!-- /automd -->

| `session.id` | `session.error`             | The request carried                                                                                                   | A cookie session's cookie    |
| ------------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| set          | `undefined`                 | a token that opened                                                                                                   | kept, or replaced by rolling |
| `undefined`  | `undefined`                 | no token                                                                                                              | none to change               |
| `undefined`  | `ERR_JWT_EXPIRED`           | an expired token                                                                                                      | expired                      |
| `undefined`  | `ERR_SESSION_TOKEN_INVALID` | a token that failed its checks, the reason as `cause`                                                                 | expired                      |
| `undefined`  | `ERR_SESSION_READ_FAILED`   | a token the session could not check: `onKeyLookup` threw or returned a key that cannot be used, that error as `cause` | kept                         |

- **401 for a dead token**: an expired token and one that fails its checks both end the session, and a cookie session's cookie is already expired, so the visitor signs in again.
- **503 for a read failure**: the token may be good and the cookie is kept, so the visitor is signed in again once the secret manager answers. `session.error.cause` is what the lookup threw, for your logs; rethrow it instead to let your own error handling answer.
- **A guest**: no `id` and no `error` is a request without a token. It is also what a session cleared in [`onRead`](/sessions/hooks#refuse-a-revoked-session) looks like.
- **Once per request**: the token is read on the first `use()`, so a later `use()` in the same request sees the same `error`.
- **After `update()` or `clear()`**: `error` is `undefined`. The `oldSession` that `onUpdate` and `onClear` receive carries it.

## When it fails

| Situation                                                                                            | What happens                                                                                                                                                                                                                        |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The token is missing                                                                                 | An empty session; `id` is `undefined`.                                                                                                                                                                                              |
| The token is expired, tampered with, under another key or not a session                              | An empty session, a cookie session's cookie expired, and `onExpire` or `onError` [fires](/sessions/hooks) with the error `session.error` then holds. `use()` does not throw. A failing header token never falls back to the cookie. |
| `onKeyLookup` throws, or returns a key that cannot be used for the token                             | An empty session, the cookie kept, and `onError` and `session.error` get `ERR_SESSION_READ_FAILED` with that error as `cause`. `use()` does not throw. The lookup's key is yours to fix, not the token.                             |
| A token whose algorithm the session doesn't accept, with `onKeyLookup` set                           | The token's failure, whatever key the lookup returns: `onError` and `session.error` get `ERR_SESSION_TOKEN_INVALID`, and a cookie session's cookie is expired.                                                                      |
| `update()` on a cookie session without a response, also when the session header holds the same token | Throws `ERR_SESSION_READONLY_EVENT`.                                                                                                                                                                                                |
| `update()` with something other than a plain object, or a `__proto__` key                            | Throws `ERR_INVALID_OPTION`.                                                                                                                                                                                                        |
| `use()` with an object that is neither a request nor `{ token }`                                     | Throws `ERR_SESSION_INVALID`.                                                                                                                                                                                                       |
| A configured `key` of the right kind that doesn't import                                             | The first `use()`, `issue()` or `open()` throws `ERR_SESSION_KEY_INVALID`. Other config errors throw when the session is defined: see [Configure a session](/sessions/configure#when-it-fails).                                     |
| A JWS and a JWE definition with the same `name` on one request                                       | The second `use()` throws `ERR_SESSION_CONFIG_INVALID`.                                                                                                                                                                             |
| `open()` on an expired token                                                                         | Throws `ERR_JWT_EXPIRED`.                                                                                                                                                                                                           |
| `open()` on any other bad token                                                                      | Throws `ERR_SESSION_TOKEN_INVALID`, the reason as its `cause`.                                                                                                                                                                      |
| `open()` when `onKeyLookup` throws or returns a key that cannot be used                              | Throws `ERR_SESSION_READ_FAILED`, that error as its `cause`.                                                                                                                                                                        |

A failed `update()` leaves the session as it was before the call, and undoes what an update function changed in place.

[Handle errors](/safety/errors) lists every code.

## Going further

- **React to reads, updates and sign-outs**: [Hooks](/sessions/hooks).
- **Clients without cookies**: [Sessions without cookies](/sessions/api-clients) covers the session header and tokens in links.
- **Your framework**: [Sessions](/sessions#pick-your-framework) points to the recipe for h3, Nitro, Nuxt and Hono, and to [Write a driver](/sessions/drivers) for any other framework.
- **Tokens for other services**: a signed session, as in [Configure a session](/sessions/configure#define-a-signed-session), can be verified with [`verify`](/jws/verify) and the public key.
