
# Write a session driver for your framework

> Run unjwt sessions on a framework it doesn't know: describe how that framework reads a request and writes a response, then define the session over it.

A session needs four things from a request, whatever the framework: a place to keep its state for that one request, a request header by name, the cookies in and out, and whether the response can still change. A driver is those four answers for one framework's request object. You write it once with `defineSessionDriver`, hand it to `defineJWSSession`, and `use()` then takes that framework's request as it is. This page builds one for Express's `req` and `res`; [Write a driver](/sessions/drivers) is the full contract.

## Before you start

- The package, and your framework:

  ```sh
  pnpm add unjwt
  ```

- A session key that survives restarts. Generate it once, in your project folder:

  ```sh
  node --input-type=module -e 'import { generateJWK } from "unjwt/jwk"; console.log(JSON.stringify(await generateJWK("HS256")))'
  ```

  It prints one line of JSON, `{"alg":"HS256","kty":"oct","k":"…","kid":"…"}`. Store that whole line as `SESSION_KEY` in your secret manager, or in a `.env` file you never commit. Whoever holds it can sign a session for any user. Replacing it signs everyone out.

- Somewhere your framework keeps values for one request only, such as Express's `res.locals`. A driver whose state outlives the request leaks one user's session into the next request.
- HTTPS, or `localhost` while you develop. The cookie is called `__Host-unjwt-jws` and carries `Secure`, so a browser drops it on plain HTTP anywhere else.

## Describe the request

Start with the shape the driver works on. Here it's the part of Express's `req` and `res` the session touches, so the driver needs no Express types and a test can build one by hand:

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

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

/** The request and response pair an Express handler receives, as far as sessions need it. */
export interface ExpressEvent {
  req: { headers: Record<string, string | string[] | undefined>; body?: unknown };
  res: {
    locals: Record<string, unknown>;
    headersSent: boolean;
    statusCode: number;
    getHeader(name: string): number | string | string[] | undefined;
    setHeader(name: string, value: string | string[]): unknown;
    end(body?: string): unknown;
  };
}
```

<!-- /automd -->

## Write the driver

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

```ts [custom-driver.ts]
export const express = defineSessionDriver<ExpressEvent>({
  prefix: "[express-session]",
  state: ({ res }) => (res.locals.sessions ??= {}) as Record<string, unknown>,
  header: ({ req }, name) => {
    const value = req.headers[name];
    return Array.isArray(value) ? value.join(", ") : value;
  },
  cookies: ({ req, res }): CookieJar<CookieAttributes> => ({
    read: (name) => parseCookies(req.headers.cookie)[name],
    written: (name) => {
      const line = setCookieLines(res).find((existing) => cookieName(existing) === name);
      return line?.slice(name.length + 1).split(";", 1)[0];
    },
    write: (name, value, attrs) => {
      const kept = setCookieLines(res).filter((existing) => cookieName(existing) !== name);
      res.setHeader("set-cookie", [...kept, serializeCookie(name, value, attrs)]);
    },
  }),
  writable: ({ res }) => !res.headersSent,
});
```

<!-- /automd -->

Each member answers one question the session asks:

- **`prefix`**: starts every error message the session throws, so a log line names your integration.
- **`state`**: an object that lives for this request only. Two `use()` calls on one request share it, so a middleware and a route read the session once between them.
- **`header`**: a request header by its lowercase name, used when the session reads a token from a header.
- **`cookies().read`**: the cookie the request sent. The session splits a long token over several cookies and asks for each by name.
- **`cookies().written`**: what this response already set for a name, so a second write in one request knows what's there. Return the value of your own `Set-Cookie` line, `""` once it was deleted.
- **`cookies().write`**: sets one cookie, replacing any line this response already has for that name, and keeps every other `Set-Cookie` line. A second `update()` in one request writes the same names again, so appending would send the browser two values.
- **`writable`**: `false` once the response has gone out. `update()` and `clear()` then throw `ERR_SESSION_READONLY_EVENT` instead of writing a cookie nobody will receive.

## Define the session and the routes

Pass the driver as the second argument. The session's `use()` then takes `{ req, res }`, typed from the driver:

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

```ts [custom-driver.ts]
const SESSION_KEY = process.env.SESSION_KEY;
if (!SESSION_KEY) throw new Error("SESSION_KEY is not set");

interface SessionData {
  user: string;
}

const config: SessionConfigJWS<SessionData, "1h", ExpressEvent> = {
  key: JSON.parse(SESSION_KEY),
  maxAge: "1h",
  rolling: "15m",
};

export const appSession = defineJWSSession(config, { driver: express });

export async function login({ req, res }: ExpressEvent) {
  const body = req.body as { user?: unknown } | undefined;
  if (typeof body?.user !== "string") return send(res, 400, { message: "user required" });
  const session = await appSession.use({ req, res });
  await session.update({ user: body.user });
  send(res, 200, { user: session.data.user });
}

export async function me({ req, res }: ExpressEvent) {
  const session = await appSession.use({ req, res });
  if (!session.id) return send(res, 401, { message: "Sign in first" });
  send(res, 200, session.data);
}

export async function logout({ req, res }: ExpressEvent) {
  const session = await appSession.use({ req, res });
  await session.clear();
  send(res, 200, { ok: true });
}
```

<!-- /automd -->

In Express, mount them with `app.post("/login", express.json(), (req, res) => login({ req, res }))`, and the same for `/me` and `/logout`; `express.json()` fills `req.body`.

- **Start-up check**: without `SESSION_KEY` the module throws before the server listens.
- **Typed by the driver**: hooks receive `{ event }` with your `ExpressEvent`, the same name they get on every other framework. See [Hooks](/sessions/hooks).
- **The rest is shared**: lifetime, rolling, chunking, expiry and every error code behave as on h3 or Hono. The driver only moves bytes in and out.

## The cookie helpers

The driver reads and writes plain `Cookie` and `Set-Cookie` text. Session tokens are base64url and dots, so they go into a cookie as they are, with no encoding:

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

```ts [custom-driver.ts]
/** `name=value` pairs of a `Cookie` header (RFC 6265 §5.4); the first of a repeated name wins. */
function parseCookies(header: string | string[] | undefined): Record<string, string> {
  const cookies: Record<string, string> = Object.create(null);
  for (const pair of String(header ?? "").split(";")) {
    const at = pair.indexOf("=");
    if (at < 1) continue;
    const name = pair.slice(0, at).trim();
    cookies[name] ??= pair.slice(at + 1).trim();
  }
  return cookies;
}

/** One `Set-Cookie` line (RFC 6265 §4.1); session values are base64url and dots, safe as they are. */
function serializeCookie(name: string, value: string, attrs: CookieAttributes): string {
  const parts = [`${name}=${value}`, `Path=${attrs.path ?? "/"}`];
  if (attrs.domain) parts.push(`Domain=${attrs.domain}`);
  if (attrs.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(attrs.maxAge)}`);
  if (attrs.expires) parts.push(`Expires=${attrs.expires.toUTCString()}`);
  if (attrs.httpOnly) parts.push("HttpOnly");
  if (attrs.secure) parts.push("Secure");
  if (attrs.sameSite) {
    const sameSite = attrs.sameSite === true ? "strict" : attrs.sameSite;
    parts.push(`SameSite=${{ strict: "Strict", lax: "Lax", none: "None" }[sameSite]}`);
  }
  if (attrs.priority) parts.push(`Priority=${attrs.priority}`);
  if (attrs.partitioned) parts.push("Partitioned");
  return parts.join("; ");
}

function setCookieLines(res: ExpressEvent["res"]): string[] {
  const current = res.getHeader("set-cookie");
  if (current === undefined) return [];
  return Array.isArray(current) ? current : [String(current)];
}

function cookieName(line: string): string {
  return line.slice(0, line.indexOf("="));
}

function send(res: ExpressEvent["res"], status: number, body: unknown): void {
  res.statusCode = status;
  res.setHeader("content-type", "application/json");
  res.end(JSON.stringify(body));
}
```

<!-- /automd -->

- **The attributes come from the session**: `attrs` already holds `Path=/`, `HttpOnly`, `Secure`, `SameSite=Lax` and the expiry, or what you set in the session's `cookie` option. Write every one you're given.
- **Deleting is a write**: `clear()` and an expired read call `write` with an empty value and `maxAge: 0`, so there's no separate delete to implement.
- **First cookie wins**: when a request carries the same name twice, the parser keeps the first, which is the one the browser sent for the most specific path.

## When it fails

| Situation                                           | What happens                                                                                                                                          |
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SESSION_KEY` unset or empty                        | The module throws `SESSION_KEY is not set` at start-up.                                                                                               |
| `update()` or `clear()` after the response was sent | `writable` returns `false`, so they throw `ERR_SESSION_READONLY_EVENT`, starting with `[express-session]`. See [Handle errors](/safety/errors).       |
| `write` appends instead of replacing                | Two `update()` calls in one request send two `Set-Cookie` lines for one cookie, and a token split over several cookies can arrive with parts of both. |
| `state` returns a shared object                     | Requests see each other's sessions. Return something that lives for one request, as `res.locals` does.                                                |
| Plain HTTP on a host other than `localhost`         | The cookie is set, the browser refuses a `Secure` cookie over HTTP, and `/me` stays 401. Serve over HTTPS.                                            |
| Request without the cookie                          | `session.id` is `undefined`, so `me` answers 401.                                                                                                     |
| Token older than `maxAge`                           | `me` answers 401, and the driver's `write` drops the cookie with `Max-Age=0`. The [`onExpire` hook](/sessions/hooks) fires.                           |
| Cookie signed with another key, or changed by hand  | Same 401 and cookie drop. The `onError` hook gets `ERR_SESSION_TOKEN_INVALID`.                                                                        |

## Going further

- **Bare `node:http`**: Node's `ServerResponse` has every member here but `locals`. Keep state in a `WeakMap` keyed by `res` instead.
- **A framework with its own cookie API**: call it from `read` and `write` instead of parsing headers, as long as `write` replaces an earlier value. See [Write a driver](/sessions/drivers).
- **Tokens that arrive another way**: a driver's optional `handed` member returns `{ token }` for events that carry the token themselves, such as a queue message. See [Write a driver](/sessions/drivers).
- **Hide the data**: `defineJWESession` takes the same `{ driver }` argument. See [Configure a session](/sessions/configure).
