
# Sessions on Hono and Workers

> Keep a signed session cookie in a Hono app on Cloudflare Workers, with the key from the Worker's secrets and one middleware that opens the session for every route.

Hono gives each request a context, `c`. The session needs two things from it: the incoming `Request`, which is `c.req.raw`, and the response Hono is preparing, `c.res`, whose headers carry the `Set-Cookie` back. A middleware opens the session once and stores it with `c.set()`, so every route reads it with `c.get("session")`. The session is a JWS, a token with a signature across it: the server can tell whether it wrote the cookie, and the user can read what's inside. [Concepts](/getting-started/concepts) has the vocabulary.

## Before you start

- Install the packages, and Wrangler to run and deploy the Worker:

  ```sh
  pnpm add hono unjwt
  pnpm add -D wrangler
  ```

- A session key that survives deploys. 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 a Worker secret with `pnpm wrangler secret put SESSION_KEY`, and for `wrangler dev` in a `.dev.vars` file you never commit, as `SESSION_KEY='…'` with the line between single quotes. Whoever holds it can sign a session for any user. Replacing it signs everyone out.

- HTTPS, or `localhost` while you develop; `wrangler dev` serves on `localhost`. The cookie is called `__Host-unjwt-jws` and carries `Secure`, so a browser drops it on plain HTTP anywhere else.

## Sign users in and out

<!-- automd:region src="../../examples/recipes/hono.ts" -->

```ts [hono.ts]
import { Hono } from "hono";
import { type SessionDefinition, type SessionManager, defineJWSSession } from "unjwt/session";

interface SessionData {
  user: string;
}

type Env = {
  Bindings: { SESSION_KEY?: string };
  Variables: { session: SessionManager<SessionData, "1h"> };
};

let appSession: SessionDefinition<SessionData, "1h"> | undefined;

/** Workers hand `env` to each request, so the session is defined on the first one. */
function sessionFor(env: Env["Bindings"]): SessionDefinition<SessionData, "1h"> {
  if (!env.SESSION_KEY) throw new Error("SESSION_KEY is not set");
  return (appSession ??= defineJWSSession<SessionData, "1h">({
    key: JSON.parse(env.SESSION_KEY),
    maxAge: "1h",
    rolling: "15m",
  }));
}

const app = new Hono<Env>();

app.use(async (c, next) => {
  const session = await sessionFor(c.env).use({ req: c.req.raw, res: c.res });
  c.set("session", session);
  await next();
});

app.post("/login", async (c) => {
  const body = await c.req.json<{ user?: unknown }>().catch(() => ({ user: undefined }));
  if (typeof body.user !== "string") return c.json({ message: "user required" }, 400);
  const session = c.get("session");
  await session.update({ user: body.user });
  return c.json({ user: session.data.user });
});

app.get("/me", (c) => {
  const session = c.get("session");
  if (!session.id) return c.json({ message: "Sign in first" }, 401);
  return c.json(session.data);
});

app.post("/logout", async (c) => {
  await c.get("session").clear();
  return c.json({ ok: true });
});

export default app;
```

<!-- /automd -->

Point `main` in your Wrangler config at this file and run `pnpm wrangler dev`. What each part does:

- **Key from `env`**: a Worker reads its secrets from `c.env`, which exists only while a request runs. So the session is defined on the first request and reused after that; every request in the same Worker sees the same secret.
- **`c.req.raw` and `c.res`**: the session reads the `Cookie` header from the raw `Request` and writes `Set-Cookie` onto the headers of `c.res`. Hono copies those headers into the response that `c.json()` builds, so the cookie leaves with it.
- **One read per request**: the middleware opens the session before any route runs, and `c.get("session")` hands every route the same one. The typed `Variables` make `c.get("session")` a session manager, not `unknown`.
- **No session yet**: `session.id` stays `undefined` until `update()` signs a first token. That's the check `/me` makes, and reading alone never sets a cookie.
- **Lifetime**: `maxAge: "1h"` ends a token an hour after it was signed. `rolling: "15m"` signs a fresh hour on the first request that finds the token at least 15 minutes old, so an active user stays in.
- **Readable data**: the cookie is `HttpOnly`, so page scripts can't read it, but the user can decode it. Keep secrets out of `update()`, or use a JWE session (see Going further).

## When it fails

| Situation                                            | What happens                                                                                                                                          |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SESSION_KEY` secret missing                         | Every request answers 500, and the Worker's log shows `SESSION_KEY is not set`. Add the secret, or the line in `.dev.vars`.                           |
| `SESSION_KEY` is not JSON                            | Every request answers 500 with a `SyntaxError` in the log. In `.dev.vars`, keep the line between single quotes.                                       |
| JSON that is not a signing key, such as a public JWK | Every request answers 500: `defineJWSSession` throws `ERR_SESSION_KEY_INVALID` in the middleware. See [Handle errors](/safety/errors).                |
| Plain HTTP on a host other than `localhost`          | `/login` answers 200 with the cookie, the browser refuses a `Secure` cookie over HTTP, and `/me` stays 401. Workers serve HTTPS on their own domains. |
| Request without the cookie                           | `session.id` is `undefined`, so `/me` answers 401.                                                                                                    |
| Token older than `maxAge`                            | The session opens empty, `/me` answers 401, and the response drops the cookie. 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`; nothing is thrown from `use()`.                                        |
| `/login` without a `user` string                     | 400, and no cookie is set.                                                                                                                            |

## Going further

- **Hide the data**: `defineJWESession` encrypts the token, so the user can't read it either. It takes an `oct` key such as `generateJWK("A256GCM")`; see [Configure a session](/sessions/configure).
- **API clients**: set `sessionHeader` so clients that call the Worker without cookies send the token in a header. A header that holds the cookie's own token keeps the request a cookie session. See [Sessions without cookies](/sessions/api-clients).
- **Revocation and audit**: hooks run when a session is read, updated, cleared or expires, for example to check a deny list in KV. See [Hooks](/sessions/hooks).
- **Other runtimes**: the same app runs on Bun, Deno and Node. There, read the key from the environment at start-up instead of from `c.env`, as the [h3](/examples/h3) recipe does.
