
# Write a driver

> Run sessions on a framework that hands its handlers its own kind of event, by telling the session where that event keeps request state, headers and cookies.

A driver is a small adapter between a session and one framework. The session knows how to read, issue and expire tokens; the driver tells it where your framework keeps the pieces of a request: a place to remember the session for this request, a request header, and the cookies. It's like a travel plug: the appliance stays the same, only the prongs change. With a driver, every page of this section applies to your framework unchanged.

## Before you start

- Check that you need one. A handler that gets a `Request` and can send back a `Headers` already works, see [Read, update and clear](/sessions/use), and h3, Nitro, Nuxt and Hono have [recipes](/sessions#pick-your-framework).
- Know where your framework keeps per-request data (often `locals` or `context`), and how it reads and sets cookies.
- The cookie API must set a cookie with the attributes the session passes, and replace an earlier `Set-Cookie` of the same cookie in the same response rather than add a second line.

## Define a driver

`defineSessionDriver` types the driver for your event, and `defineJWESession` or `defineJWSSession` from `unjwt/session` take it as `{ driver }`:

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

```ts [custom-driver.ts]
import {
  type CookieAttributes,
  type CookieJar,
  defineJWESession,
  defineSessionDriver,
} from "unjwt/session";

/** The event your framework hands each handler. */
export interface AppEvent {
  request: Request;
  /** Created for this request alone. */
  locals: { sessions?: Record<string, unknown> };
  /** `get` already sees what `set` wrote earlier in the same request. */
  cookies: {
    get(name: string): string | undefined;
    set(name: string, value: string, options: CookieAttributes): void;
  };
  /** `true` once the response has gone out. */
  sent: boolean;
}

const appDriver = defineSessionDriver<AppEvent>({
  prefix: "[app-session]",
  state: (event) => (event.locals.sessions ??= {}),
  header: (event, name) => event.request.headers.get(name),
  cookies: (event): CookieJar<CookieAttributes> => ({
    read: (name) => event.cookies.get(name),
    write: (name, value, attrs) => event.cookies.set(name, value, attrs),
  }),
  writable: (event) => !event.sent,
});

// const key = the "oct" JWK from SESSION_KEY (see Configure a session)

export const appSession = defineJWESession<{ userId: string }, "7D", AppEvent>(
  { key, maxAge: "7D" },
  { driver: appDriver },
);
```

<!-- /automd -->

- **The event type**: `use()` and `token()` take an `AppEvent`, and every hook receives it as `event`.
- **`state`**: the session is remembered in `locals.sessions`, which the framework creates for each request.
- **`cookies`**: the framework's own `get` and `set`. `CookieJar<CookieAttributes>` types the attributes `write` receives.
- **`writable`**: once the response is out, `update()` and `clear()` throw instead of writing a cookie nobody sends.

## What each member does

| Member                | Required | The session calls it                                                                                                 | It must return                                                                        |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `prefix`              | yes      | at the start of every error message                                                                                  | A string such as `"[app-session]"`.                                                   |
| `state(event)`        | yes      | on every `use()` and `token()`                                                                                       | The same object for every call on one request, and a different one for every request. |
| `header(event, name)` | yes      | when `sessionHeader` is set, with the header name in lowercase                                                       | The header's value, or `null` or `undefined` when the request has none.               |
| `cookies(event)`      | yes      | on every request unless `cookie` is `false`, also to compare the cookie with a session header                        | A [`CookieJar`](#the-cookie-jar) for this request and its response.                   |
| `writable(event)`     | no       | on a cookie session: before `update()` and `clear()`, before `rolling` reissues, before an expired cookie is removed | `false` once the response was sent. Absent, the response always counts as open.       |
| `handed(event)`       | no       | first, before any header or cookie                                                                                   | `{ token }` when the event carries the token itself, else `undefined`.                |

`state` is where most driver bugs hide. Return a module-level object, or one that concurrent requests share, and one visitor's session is served to the next. Return a new object on every call, and a second `use()` in the same request reads the token again instead of seeing the first call's update.

`handed` is for events that are a token rather than a request, such as a message in a queue. For such an event `session.source` is `"token"`: the session reads that token, writes nothing and never rolls it. `update()` puts the new token on `session.token` and sending it is your job, whatever `cookie` and `sessionHeader` say.

## The cookie jar

| Member                      | Required | Does                                                                                                                                                                                                      |
| --------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read(name)`                | yes      | Returns the request's cookie of that name, or `undefined`.                                                                                                                                                |
| `write(name, value, attrs)` | no       | Sets the cookie on the response, replacing an earlier write of the same cookie. Absent, the event takes no cookie: `update()` throws `ERR_SESSION_READONLY_EVENT` and `clear()` only empties the session. |
| `written(name)`             | no       | Returns what this response already set for `name`, `""` once deleted. Needed only when `read` does not see this response's writes.                                                                        |

- **One cookie at a time**: a split token arrives as the base cookie and then `<name>.1` to `<name>.N`; removing a session writes `""` with `maxAge: 0` and an `expires` in 1970 for each of them.
- **Replace, never append**: a second `update()` in the same request writes the same names again. A `write` that only appends leaves the old value in the response next to the new one.
- **`attrs`**: `path`, `secure`, `httpOnly`, `sameSite`, `expires`, `maxAge`, `domain`, `priority` and `partitioned`, as [Change cookie attributes](/sessions/configure#change-cookie-attributes) sets them. Pass them on as they are.

## The Web driver

`webSessionDriver(options?)` returns the driver `defineJWSSession` and `defineJWESession` run on when you pass none. It is the reference implementation of this contract, over a Web `Request`:

| Member     | The Web driver                                                                                                                                                                      |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prefix`   | `options.prefix`, `"[unjwt/session]"` when unset.                                                                                                                                   |
| `state`    | `event.context.unjwt` when the event has a `context`, created on first use and kept when it is already an object; else a record for the event's `Request`, or for the event itself. |
| `header`   | From `event.req.headers`, else `event.headers`.                                                                                                                                     |
| `cookies`  | [`webCookieJar`](#cookies-without-a-session) over the request's headers and `event.res`. Without `res` the jar only reads.                                                          |
| `writable` | Absent: a Web response has no signal that it was sent.                                                                                                                              |
| `handed`   | `{ token }` for an event with `token` and neither `req` nor `headers`.                                                                                                              |

- **The events it takes**: `{ req, res?, context? }`, `{ headers, res?, context? }` and `{ token }`. Any other shape, or a `req` whose `headers` are not Web `Headers` (a Node request), throws `ERR_SESSION_INVALID`.
- **`prefix`**: starts the message of every error a session over this driver throws, the driver's own refusals included. A session defined with `{ driver: webSessionDriver({ prefix: "[billing]" }) }` starts its messages with `[billing]` where the default one starts them with `[unjwt/session]`. Nothing else changes.
- **One state per request**: every driver `webSessionDriver` returns reads the same state for a request, whatever its prefix. A JWS and a JWE session over two of them still cannot use one name on the same request.
- **Beyond the built-in sessions**: the driver also runs a session you write yourself, see [Build a session of your own](/sessions/custom-session).

## Cookies without a session

The cookie layer the Web driver uses is yours for any other cookie, such as a theme or a CSRF value, from `unjwt/session`:

| Function                               | Returns                                                                                                     |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `webCookieJar(request, response?)`     | A [`CookieJar`](#the-cookie-jar) over a request's `Headers` and `{ headers, errHeaders? }` of its response. |
| `parseCookie(header)`                  | The cookies of a `Cookie` header value, by name.                                                            |
| `serializeCookie(name, value, attrs?)` | One `Set-Cookie` line.                                                                                      |

- **`read`**: the jar parses the request's `Cookie` header once. Values are percent-decoded, and of two cookies with one name the first wins.
- **`write` replaces, never appends**: it sets one `Set-Cookie` line on `response.headers` and removes an earlier line of the same cookie, the same name, domain, path and `partitioned` flag. A cookie of the same name on another path keeps its own line, and every other line stays.
- **`written`**: what this response sets for a name, `""` once deleted. Without `response` the jar has neither `write` nor `written`.
- **`errHeaders`**: each write is copied there too, replacing that cookie's lines. h3 and Nitro send only these headers for a handler that throws, so a cookie set before the throw still reaches the browser.
- **`parseCookie`**: returns a record without a prototype, so a cookie named `constructor` is the only `constructor` in it. A value that does not decode is kept as sent.
- **`serializeCookie`**: percent-encodes the value and adds `Path=/` unless `attrs.path` sets another. It renders every [cookie attribute](/sessions/configure#change-cookie-attributes) the session uses, `sameSite: true` as `Strict`. It throws a `TypeError` for a name or attribute the cookie standard refuses, such as a name with a space, a fractional `maxAge`, or `sameSite: "none"` without `secure`.

## When it fails

| Situation                                                             | What happens                                                                                                            |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `writable` returns `false`                                            | On a cookie session, `update()` and `clear()` throw `ERR_SESSION_READONLY_EVENT`; `rolling` waits for the next request. |
| The jar has no `write`                                                | `update()` throws `ERR_SESSION_READONLY_EVENT`, `clear()` empties the session for this request.                         |
| `state` shared between requests                                       | No error: sessions leak between visitors. Test two requests side by side.                                               |
| `read` does not see this response's writes, and there is no `written` | A second `update()` in one request that shortens a split token can leave its unused parts in the browser.               |

Errors carry your `prefix` at the start of their message. [Handle errors](/safety/errors) lists every code.

## Going further

- **A complete driver, step by step**: [Write a session driver for your framework](/examples/custom-driver).
- **The session itself**: [Configure a session](/sessions/configure) and [Hooks](/sessions/hooks) work the same over any driver.
- **A session of another kind over the same transport**: [Build a session of your own](/sessions/custom-session).
