
# Build a session of your own

> Write another kind of session, such as one whose cookie holds a random token and whose data sits in your store, that finds its token and writes its cookie exactly as `defineJWESession` does.

`defineJWSSession` and `defineJWESession` keep the data in the token. When the data lives somewhere else, say a database row keyed by a random token, you write the session yourself, but you don't have to rewrite how it travels. The same parts the built-in sessions run on are yours to call: a check of the config when the session is defined, and, on every request, a claim on its name and a transport that finds the token in a token you hand in, the session header or the cookie, and writes the cookie back. It's like reusing a building's mailroom for a new department: what's in the envelopes is yours, the sorting and delivery stay the same.

## Before you start

- Check that you need one. A session whose data fits in about 4 KB of cookie and needs no server-side lookup is `defineJWESession`, see [Configure a session](/sessions/configure). The built-in sessions also give you hooks, `rolling`, keys and rotation, which you would rebuild here.
- These parts move the token and nothing else. Making the token, storing the data, expiring and revoking sessions are yours.
- The [Web driver](/sessions/drivers#the-web-driver) reads `{ req, res }`, `{ headers }` and `{ token }` events. For a framework with its own event, [write a driver](/sessions/drivers) and pass it in its place.

## The pieces

All of them come from `unjwt/session`:

| Piece                                                             | Call it                                  | It does                                                                                          |
| ----------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `webSessionDriver({ prefix })`                                    | once, at start-up                        | Reads a Web request event, and starts every error message with `prefix`.                         |
| `frozenCopy(config)`                                              | once, when the session is defined, first | Returns a copy of the config, typed `ReadonlyConfig`, whose plain objects and arrays are frozen. |
| `assertSessionConfig(config, options)`                            | once, when the session is defined        | Refuses a name, session header, cookie prefix or `rolling` that cannot work.                     |
| `sessionTransportOptions(config, { name, defaultCookie })`        | once, when the session is defined        | Builds the transport's options from the config's cookie and session header.                      |
| `claimSessionName(driver.state(event), { name, family, prefix })` | on every request, before the transport   | Refuses a name another session kind already uses on this request.                                |
| `resolveSessionTransport(driver, event, options)`                 | on every request                         | Decides where this request's token comes from, and returns how to read and write it.             |
| `assertSessionTokenSource(transport, { prefix })`                 | before reading                           | Refuses a session with neither a cookie nor a session header.                                    |
| `assertSessionWritable(transport, options)`                       | before each update and clear             | Refuses an update or a clear the response can no longer carry.                                   |

## Check the config when the session is defined

Call `frozenCopy(config)` once, before `assertSessionConfig`, and check and run the session on the copy it returns, so a later change to the object your caller passed has no effect.

`assertSessionConfig(config, { name, prefix, defaultCookie })` returns nothing and throws on the first problem it finds, so a bad config stops your server at start-up rather than on the first request. `defaultCookie` is optional: unset, it is `DEFAULT_SESSION_COOKIE`, the attributes the built-in sessions write with (`path "/"`, `secure`, `httpOnly`, `sameSite "lax"`). It checks what the config alone decides:

- **`name`**: a valid cookie name that does not end in a dot and digits, such as `app.1`, which spells a part of a split cookie.
- **`config.sessionHeader`**: `true`, `false`, unset, or a valid header name.
- **The cookie prefix**: a `__Host-` name needs `secure`, no `domain` and a `path` of `"/"`; a `__Secure-` name needs `secure`. A missing `secure` fails like `secure: false`, so a `defaultCookie` of your own needs it; `DEFAULT_SESSION_COOKIE` has it. The attributes checked are `defaultCookie` with `config.cookie` over it, the same merge your session writes with, so a config that only sets `httpOnly` still meets your defaults. With `cookie: false` there is no cookie to check.
- **`config.rolling`**: either `true` or a duration shorter than `maxAge`.

Each error is a `JWTError` with code `ERR_SESSION_CONFIG_INVALID` whose message starts with `prefix`; a `rolling` that is neither `true` nor a duration throws `ERR_INVALID_OPTION`. `SessionConfigChecks` types the members it reads, and every config of `defineJWSSession` and `defineJWESession` fits it.

## Claim the name on every request

One name is one cookie, so two kinds of session cannot share it on a request. `claimSessionName(driver.state(event), { name, family, prefix })` records the name for the request under `family`, a word for your kind of session such as `"stored"`; the built-in sessions claim theirs as `"jws"` and `"jwe"`. The first kind to claim a name on a request keeps it: the same kind may claim it again, as a second `use()` does, and another kind throws `ERR_SESSION_CONFIG_INVALID` whose message starts with `prefix`. Call it before `resolveSessionTransport`.

## Find the token on every request

`resolveSessionTransport(driver, event, options)` decides, before any token is read, where this request's token comes from, and records it in `source`:

1. **`"token"`**: the driver hands the token in, as the Web driver does for `{ token }`. Nothing else is looked at.
2. **`"header"`**: `options.sessionHeader` is set and the request sends that header, unless the header holds the very token of the request's cookie. The cookie is then neither read nor written.
3. **`"cookie"`**: everything else, including a header that holds the cookie's token.

With `cookie: false` the source is `"header"` whether or not the header is sent.

What the transport lets you do follows from the source:

| Source     | `read()` returns                                                      | `write`, `assertFits` and `drop`       | `readonly`               |
| ---------- | --------------------------------------------------------------------- | -------------------------------------- | ------------------------ |
| `"token"`  | The token handed in.                                                  | Absent.                                | `false`                  |
| `"header"` | The header's token, `undefined` when it holds none.                   | Absent.                                | `false`                  |
| `"cookie"` | The cookie this response wrote, else the request's, its parts joined. | Present when the event has a response. | `true` when it has none. |

- **Header values**: the token alone or `Bearer <token>`, `Bearer` in any case. Any other value, such as `Basic …`, still makes a `"header"` request: `read()` returns `undefined` and `malformed` holds `{ header }`, the name of the header that was sent without a token. Your session decides how to report it; the built-in sessions report `ERR_SESSION_TOKEN_INVALID`.
- **The header name**: `sessionHeader: true` reads `x-<name>-session`, the name lowercased and without its `__Host-` or `__Secure-` prefix, so `__Host-app` reads `x-app-session`. A string names the header itself.
- **Write the cookie**: `write(token)` sets it with `options.cookie.attrs`, split into `<name>.1` to `<name>.N` past `chunkMaxLength` characters (`4000` when unset), and expires the leftover parts of a longer earlier token. `write(token, { expiresAt })`, in milliseconds, sets `expires` to that time and drops `maxAge`, which browsers would otherwise follow instead.
- **Check that it fits**: a token that needs more than 16 parts cannot be written. `assertFits(token)` throws the error `write` throws for it, `ERR_SESSION_INVALID`, and writes nothing. Call it once the token is issued and before your own hooks or store writes, so none of them run for a token the cookie cannot carry.
- **Remove the cookie**: `drop()` expires the cookie and every part, with `Max-Age=0` and an `expires` in 1970.
- **A second read sees the first write**: `read()` on a cookie session returns what this response already wrote, and nothing once it was dropped, so a second `use()` in one request finds the token the first one issued.
- **`writable()`**: `false` once the response was sent, as the driver reports it. The Web driver always answers `true`. From then on `write` and `drop` return `false` and write nothing.

## Refuse what the request cannot do

`assertSessionTokenSource(transport, { prefix })` throws `ERR_SESSION_CONFIG_INVALID` when `read` is absent: the options have `cookie: false` and no `sessionHeader`, so no request can carry a token. After it, TypeScript knows `read` is there.

`assertSessionWritable(transport, { operation, prefix })` treats an update and a clear differently:

| Situation                                                   | `operation: "update"`                | `operation: "clear"`                 |
| ----------------------------------------------------------- | ------------------------------------ | ------------------------------------ |
| A cookie session whose event has no response (`readonly`)   | Throws `ERR_SESSION_READONLY_EVENT`. | Passes.                              |
| `writable()` returns `false`                                | Throws `ERR_SESSION_READONLY_EVENT`. | Throws `ERR_SESSION_READONLY_EVENT`. |
| A `"token"` or `"header"` session, or a cookie it can write | Passes.                              | Passes.                              |

An update that cannot reach the client would leave the browser on its old cookie while your store moved on, so it throws. A clear on a read-only event can still forget the session on your side, and the cookie stays until a later request removes it. `drop` is absent there, as on a `"token"` or `"header"` session, so call it as `drop?.()`.

## The transport's members

`resolveSessionTransport` returns a `SessionTransport`:

| Member                        | Type                                                           | Present                             | Holds                                                                                                                                                             |
| ----------------------------- | -------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`                      | `"token"` \| `"header"` \| `"cookie"`                          | always                              | Where this request's token comes from.                                                                                                                            |
| `read()`                      | `() => string \| undefined`                                    | with a token source                 | The token, or `undefined` when the request carries none.                                                                                                          |
| `malformed`                   | `{ header: string }`                                           | when the header holds no token      | The lowercase name of the header that was sent without a token.                                                                                                   |
| `write(token, { expiresAt })` | `(token: string, options?: { expiresAt?: number }) => boolean` | on a cookie session with a response | Sets the cookie and returns `true`; `false`, writing nothing, once the response was sent. Throws `ERR_SESSION_INVALID` for a token that needs more than 16 parts. |
| `assertFits(token)`           | `(token: string) => void`                                      | on a cookie session with a response | Checks that `write` can take the token, and writes nothing. Throws `ERR_SESSION_INVALID` for a token that needs more than 16 parts.                               |
| `drop()`                      | `() => boolean`                                                | on a cookie session with a response | Expires the cookie and every part and returns `true`; `false`, writing nothing, once the response was sent.                                                       |
| `readonly`                    | `boolean`                                                      | always                              | `true` for a cookie session whose event has no response.                                                                                                          |
| `writable()`                  | `() => boolean`                                                | always                              | `false` once the response was sent.                                                                                                                               |

## The transport's options

`resolveSessionTransport` takes a `SessionTransportOptions` as its third argument:

| Member          | Type                                                            | Required | Does                                                                                                        |
| --------------- | --------------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| `name`          | `string`                                                        | yes      | The cookie name, and the base of the `x-<name>-session` header.                                             |
| `sessionHeader` | `boolean \| string`                                             | no       | `true` reads `x-<name>-session`, a string reads that header. Unset or `false`, no header is read.           |
| `cookie`        | `false \| { attrs: CookieAttributes; chunkMaxLength?: number }` | yes      | The attributes every cookie write uses, as they are, and the part size. `false` reads and writes no cookie. |

`attrs` is written as given. `sessionTransportOptions(config, { name, defaultCookie })` builds these options from a config that `assertSessionConfig` checks: `config.cookie` over `defaultCookie` (`DEFAULT_SESSION_COOKIE` when unset) as `attrs`, its `chunkMaxLength` as the part size, and `config.sessionHeader`. `cookie: false` stays `false`. Pass both the same `defaultCookie`, so the cookie you write is the one that was checked.

## A session backed by your store

This session keeps its data in a store, keyed by the digest of a random 32-byte token the cookie carries. It reads the cookie, the `x-app-session` header or a token in hand, and issues a fresh token on every update:

<!-- automd:region src="../../examples/sessions/custom-session.ts" -->

```ts [custom-session.ts]
import {
  type CookieAttributes,
  type WebSessionEvent,
  assertSessionConfig,
  assertSessionTokenSource,
  assertSessionWritable,
  claimSessionName,
  frozenCopy,
  resolveSessionTransport,
  sessionTransportOptions,
  webSessionDriver,
} from "unjwt/session";
import { base64UrlStringify, secureRandomBytes } from "unjwt/utils";
import { hash } from "unsecure/hash"; // WebCrypto API

// const store = your session store: a database table, Redis, a KV namespace

export interface StoredSessionConfig {
  /** The cookie name, and the base of the `x-<name>-session` header. */
  name: string;
  /** Seconds a session lives after its last update. */
  maxAge?: number;
  sessionHeader?: boolean | string;
  cookie?: false | (CookieAttributes & { chunkMaxLength?: number });
}

const driver = webSessionDriver({ prefix: "[app-session]" });
const { prefix } = driver;

export function defineStoredSession<T extends Record<string, unknown>>(
  configured: StoredSessionConfig,
) {
  const config = frozenCopy(configured);
  const { name, maxAge = 7 * 24 * 60 * 60 } = config;
  assertSessionConfig(config, { name, prefix });
  const transportOptions = sessionTransportOptions(config, { name });

  return {
    async use(event: WebSessionEvent) {
      claimSessionName(driver.state(event), { name, family: "stored", prefix });
      const transport = resolveSessionTransport(driver, event, transportOptions);
      assertSessionTokenSource(transport, { prefix });

      const token = transport.read();
      const id = token === undefined ? undefined : await hash(token);
      const entry = id === undefined ? undefined : await store.get(id);
      const live = entry && entry.expiresAt > Date.now() ? entry : undefined;
      if (id !== undefined && !live) {
        await store.delete(id);
        transport.drop?.();
      }

      const session = {
        source: transport.source,
        id: live ? id : undefined,
        token: live ? token : undefined,
        data: (live?.data ?? {}) as Partial<T>,
        async update(data: Partial<T>) {
          assertSessionWritable(transport, { operation: "update", prefix });
          if (session.id) await store.delete(session.id);
          const fresh = base64UrlStringify(secureRandomBytes(32));
          const freshId = await hash(fresh);
          const expiresAt = Date.now() + maxAge * 1000;
          session.data = { ...session.data, ...data };
          await store.set(freshId, { data: session.data, expiresAt });
          transport.write?.(fresh, { expiresAt });
          session.id = freshId;
          session.token = fresh;
        },
        async clear() {
          assertSessionWritable(transport, { operation: "clear", prefix });
          if (session.id) await store.delete(session.id);
          transport.drop?.();
          session.id = undefined;
          session.token = undefined;
          session.data = {};
        },
      };
      return session;
    },
  };
}

export const appSession = defineStoredSession<{ userId: string }>({
  name: "__Host-app",
  maxAge: 24 * 60 * 60,
  sessionHeader: true,
});
```

<!-- /automd -->

- **Defined once**: `defineStoredSession` runs `assertSessionConfig` and `sessionTransportOptions` over the same `DEFAULT_SESSION_COOKIE`, so a `__Host-` name with `cookie: { secure: false }` throws `ERR_SESSION_CONFIG_INVALID` starting with `[app-session]` before the server listens.
- **A token nobody knows**: an unknown or expired token reads as an empty session, and its cookie is dropped when the response can still take it. A header or a token in hand has no cookie to drop.
- **A new token on every update**: `update()` deletes the old entry and issues a new one, so a token copied before sign-in is worthless after it. `write(id, { expiresAt })` makes the cookie expire with the entry.
- **Hashed in the store**: the cookie carries the token, the store is keyed by its SHA-256 digest, and `id` is that digest. A copy of the store signs nobody in.
- **Header and token sessions**: `update()` writes no cookie there; the new token is `session.token`, and handing it back is your job, as in [Sessions without cookies](/sessions/api-clients).
- **Two `use()` calls in one request**: on a cookie session the second reads the token the first one wrote. To share one session object between a middleware and a handler instead, keep it in `driver.state(event)`, a record unique to the request.

## When it fails

| Situation                                               | What happens                                                                                                              |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| A bad name, session header, cookie prefix or `rolling`  | `assertSessionConfig` throws `ERR_SESSION_CONFIG_INVALID`, or `ERR_INVALID_OPTION` for a `rolling` that isn't a duration. |
| A name another session kind already uses on the request | `claimSessionName` throws `ERR_SESSION_CONFIG_INVALID`.                                                                   |
| `cookie: false` and no `sessionHeader`                  | `assertSessionTokenSource` throws `ERR_SESSION_CONFIG_INVALID`.                                                           |
| An event that is neither a request nor `{ token }`      | The Web driver throws `ERR_SESSION_INVALID` from `resolveSessionTransport`.                                               |
| A header that holds no token, such as `Basic …`         | `read()` returns `undefined` and `malformed` holds `{ header }`, for your session to report. The cookie is not read.      |
| An update on a cookie session read without a response   | `assertSessionWritable` throws `ERR_SESSION_READONLY_EVENT`. A clear passes, and `drop` is absent.                        |
| An update or a clear once the response was sent         | `assertSessionWritable` throws `ERR_SESSION_READONLY_EVENT`.                                                              |
| A token that needs more than 16 cookie parts            | `assertFits` and `write` throw `ERR_SESSION_INVALID`, and write nothing.                                                  |

Every message starts with the `prefix` you passed, or the driver's. [Handle errors](/safety/errors) lists every code.

## Going further

- **Another framework**: [Write a driver](/sessions/drivers) and pass it to `resolveSessionTransport` in place of `webSessionDriver()`.
- **The options your config can mirror**: [Configure a session](/sessions/configure) describes `name`, `cookie` and `sessionHeader` as the built-in sessions use them.
- **Clients that send a header**: [Sessions without cookies](/sessions/api-clients) covers the flows a header session serves.
- **Every error code**: [Handle errors](/safety/errors).
