
# Sessions without cookies

> Keep a session for a command-line tool, a service account or an app that sends its token in a request header, and open tokens that arrive in a link or a message.

A browser carries a session for you: it stores the cookie and sends it back with every request. A command-line tool, a CI job or a mobile app keeps no cookie jar, so it carries the token itself, like a hotel guest who keeps the key card in their own pocket instead of leaving it at the desk. The session works the same either way, with the same key, data, expiry and hooks, whether it signs or encrypts its token. What changes is the way back: nothing writes a new token to the client for you, so your response hands it over. [Sessions](/sessions#where-the-token-comes-from) explains how a request picks its token.

## Before you start

- Name the header in the config: `sessionHeader: "x-acme-session"`, or `sessionHeader: true` for `x-<name>-session`, which is `x-unjwt-jws-session` for the default signed session. Without `sessionHeader` no header is read.
- The client keeps the token as it keeps a password, in the system keychain or the CI secret store. Whoever holds it is signed in until it expires.
- A session read from the header or from a token in hand writes nothing back, and `rolling` never reissues it. A new token reaches the client only in a response you build.

## Sign in a command-line tool

A deploy tool signs in with a service account's credentials, gets a token back in the JSON body, and sends it in `x-acme-session` on every later call. The session reads that header and nothing else:

<!-- automd:region src="../../examples/sessions/api-client.ts" -->

```ts [api-client.ts]
import { defineJWSSession } from "unjwt/session";

// const key = an HS256 JWK loaded at start-up (see Configure a session)

export interface ApiSession {
  accountId: string;
  scope: "read" | "write";
}

export const apiSession = defineJWSSession<ApiSession, "1h">({
  key,
  maxAge: "1h",
  cookie: false,
  sessionHeader: "x-acme-session",
});
```

<!-- /automd -->

- **`cookie: false`**: the session never reads or writes a cookie, so every request is read from the header.
- **`sessionHeader`**: the header holds the token alone or `Bearer <token>`, and `Bearer` may be in any case. Header names are case-insensitive.
- **One hour**: `maxAge` ends each token an hour after it was issued, however often the tool calls.

The handlers mint the token at login, read it on every call and refresh it on request:

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

```ts [api-client.ts]
/** `POST /login` with `{ clientId, clientSecret }`: the token goes back in the body. */
export async function login(req: Request) {
  const { clientId, clientSecret } = await req.json();
  const account = await findServiceAccount(clientId, clientSecret);
  if (!account) return Response.json({ error: "invalid_client" }, { status: 401 });
  const token = await apiSession.issue({ accountId: account.id, scope: account.scope });
  return Response.json({ token });
}

/** `GET /me`: the client sends `x-acme-session: Bearer <token>`. */
export async function me(req: Request) {
  const session = await apiSession.use({ req });
  if (!session.id) return Response.json({ error: "unauthorized" }, { status: 401 });
  return Response.json(session.data);
}

/** `POST /refresh`: a fresh hour on a new token, which the client keeps in place of the old one. */
export async function refresh(req: Request) {
  const session = await apiSession.use({ req });
  if (!session.id) return Response.json({ error: "unauthorized" }, { status: 401 });
  await session.update();
  return Response.json({ token: session.token, expiresAt: session.expiresAt });
}

/** `POST /logout`: the client deletes its copy; the token itself stays valid until it expires. */
export async function logout(req: Request) {
  const session = await apiSession.use({ req });
  await session.clear();
  return new Response(null, { status: 204 });
}
```

<!-- /automd -->

- **Login**: `issue()` mints a token from the data you give it and reads no request. Checking the credentials is your code.
- **No response headers**: `use({ req })` is enough, because a header session has nothing to write. `use({ headers })` takes the request's `Headers` alone. `session.source` is `"header"`.
- **Refresh**: `update()` issues a token with a fresh `id` and expiry onto `session.token`, and the handler returns it. The old token keeps working until it expires. `session.token` is the session's own token, never one that failed to open; [Two views of the token](/sessions/use#two-views-of-the-token) sets it beside `token(event)`.
- **Logout**: `clear()` empties the session for this request. The token the client sent is still valid until it expires, so the client deletes its copy; to refuse a token before then, check it in [`onRead`](/sessions/hooks#refuse-a-revoked-session).

## Send the token from the client

The tool keeps the token from the login body, sends it on every call, swaps it after a refresh and forgets it on logout:

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

```ts [api-client.ts]
/** The command-line side: sign in once, keep the token, send it on every call. */
export function acmeClient(options: { baseUrl: string; fetch?: typeof fetch }) {
  const send = options.fetch ?? fetch;
  let token: string | undefined;

  const call = (path: string, init: RequestInit = {}): Promise<Response> => {
    const headers = new Headers(init.headers);
    if (token) headers.set("x-acme-session", `Bearer ${token}`);
    return send(new URL(path, options.baseUrl), { ...init, headers });
  };

  return {
    async login(clientId: string, clientSecret: string): Promise<void> {
      const body = JSON.stringify({ clientId, clientSecret });
      const response = await call("/login", { method: "POST", body });
      if (!response.ok) throw new Error(`login failed: ${response.status}`);
      ({ token } = await response.json());
    },
    async refresh(): Promise<void> {
      const response = await call("/refresh", { method: "POST" });
      if (response.ok) ({ token } = await response.json());
    },
    async logout(): Promise<void> {
      await call("/logout", { method: "POST" });
      token = undefined;
    },
    me: () => call("/me"),
  };
}
```

<!-- /automd -->

Refresh before the hour is up: a token past its expiry gets a `401`, and the tool signs in again. To tell the tool why its token was refused, answer from `session.error`, as [Tell what happened to the token](/sessions/use#tell-what-happened-to-the-token) does.

## Open a token from a link or a message

A sign-in link in an email, an email confirmation or a job in a queue carries the token in its own envelope, not in a header. `issue()` mints it and `open()` reads it back, with no request involved:

<!-- 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 -->

- **No token source**: `cookie: false` and `sessionHeader: false` mean no request carries this token by accident. `use(req)` on this definition throws `ERR_SESSION_CONFIG_INVALID`, while `issue()`, `open()` and `use({ token })` work.
- **`open()` throws**: an expired token throws `ERR_JWT_EXPIRED` and any other bad token `ERR_SESSION_TOKEN_INVALID`. It returns `{ id, createdAt, expiresAt, data, source }`, with `source` always `"token"`.
- **`use({ token })` instead**: it runs the hooks and gives an empty session for a bad token rather than throwing, with `session.source` set to `"token"`. `update()` re-mints onto `session.token`, and sending it on is your job. [Use a token you hold](/sessions/use#use-a-token-you-hold) has an example.

## Mirror the cookie into a header

A browser app that serves both the page and API clients may send the session header from its own `fetch` calls too. The page cannot read an `HttpOnly` cookie, so it mirrors the token from a response. When the header and the cookie hold the same token, the request is a cookie session: `update()` writes the cookie, `rolling` reissues it, and a token that fails its checks has its cookie expired:

<!-- automd:region src="../../examples/sessions/mirrored-header.ts" -->

```ts [mirrored-header.ts]
import { defineJWESession } from "unjwt/session";

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

/** The header the page sends and the response answers with: `x-<name>-session`. */
const SESSION_HEADER = "x-unjwt-jwe-session";

export const webSession = defineJWESession<{ userId: string }, "1h">({
  key,
  maxAge: "1h",
  rolling: "15m",
  sessionHeader: true,
});

/** Call once your own credential check has passed: the cookie for the browser, the token for the page. */
export async function signIn(req: Request, userId: string) {
  const headers = new Headers();
  const session = await webSession.use({ req, res: { headers } });
  await session.update({ userId });
  return Response.json({ token: session.token }, { headers });
}

/** Any later request: when the token changed, the page gets the new one to mirror. */
export async function profile(req: Request) {
  const headers = new Headers();
  const session = await webSession.use({ req, res: { headers } });
  if (!session.id) return new Response("Sign in first", { status: 401, headers });
  if (session.token && session.token !== req.headers.get(SESSION_HEADER)) {
    headers.set(SESSION_HEADER, session.token);
  }
  return Response.json({ userId: session.data.userId, source: session.source }, { headers });
}
```

<!-- /automd -->

- **Keep the copy current**: a rolling reissue or an `update()` changes the cookie, and the copy the page holds stops matching. A request that sends the stale copy runs on the header, with no cookie written and no rolling. `profile` answers with the new token whenever it differs from the header, and the page swaps its copy.
- **A page without its copy**: after a reload the page sends no header, the request runs on the cookie, and the response hands the token back.
- **Sign-out**: drop the page's copy along with the cookie. A header that is still sent after `clear()` reads that token on its own, signed in until it expires.
- **Scripts can read it**: the page holds the token, so a script injected into the page can read it too. The `HttpOnly` cookie alone keeps it out of their reach.

## Override the cookie with a header

A developer signed in as one user in the browser can test as another by sending that user's token in the header. A header that holds a different token from the cookie wins on its own: the request reads the header, as the other user, and the cookie is neither read nor written. A failing header token gives an empty session and never falls back to the cookie. [Configure a session](/sessions/configure#accept-the-token-in-a-header) has the full table of what each request reads and what `update()` reaches.

## When it fails

| Situation                                                                                         | What happens                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No header, or a token that is expired or tampered with                                            | An empty session; `id` is `undefined`. `onExpire` or `onError` [fires](/sessions/hooks), and `session.error` holds the same error.                                              |
| A header that holds no token, such as `Basic …`                                                   | It counts as sent: an empty session, `onError` with `ERR_SESSION_TOKEN_INVALID`, and the cookie is not read.                                                                    |
| A header token that is expired or bad, with a valid cookie                                        | An empty session. The cookie is not read and not removed.                                                                                                                       |
| A header that differs from the cookie                                                             | The header alone is read; `update()` writes no cookie and `rolling` does not reissue.                                                                                           |
| `update()` on a cookie session read without a response, also when the header holds the same token | Throws `ERR_SESSION_READONLY_EVENT`, as for a WebSocket upgrade. A header that differs from the cookie is a header session, and `update()` re-mints onto `session.token` there. |
| `cookie: false` and no `sessionHeader`                                                            | `use()` and `token()` on a request throw `ERR_SESSION_CONFIG_INVALID`. `use({ token })`, `issue()` and `open()` work.                                                           |
| `cookie: false` and the request sends no header                                                   | An empty session. `update()` still issues onto `session.token`.                                                                                                                 |

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

## Going further

- **Refresh, not rolling**: `rolling` applies to cookie sessions alone. Give API clients a refresh endpoint that calls `update()`, as above.
- **Refuse a token early**: [Hooks](/sessions/hooks#refuse-a-revoked-session) checks a revocation list in `onRead` and branches on `session.source`.
- **A framework with its own header API**: [Write a driver](/sessions/drivers) tells the session how to read a header from your framework's event.
