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 has the vocabulary.
#Before you start
Install the packages, and Wrangler to run and deploy the Worker:
pnpm add hono unjwt pnpm add -D wranglerA session key that survives deploys. Generate it once, in your project folder:
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 withpnpm wrangler secret put SESSION_KEY, and forwrangler devin a.dev.varsfile you never commit, asSESSION_KEY='…'with the line between single quotes. Whoever holds it can sign a session for any user. Replacing it signs everyone out.HTTPS, or
localhostwhile you develop;wrangler devserves onlocalhost. The cookie is called__Host-unjwt-jwsand carriesSecure, so a browser drops it on plain HTTP anywhere else.
#Sign users in and out
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;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 fromc.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.rawandc.res: the session reads theCookieheader from the rawRequestand writesSet-Cookieonto the headers ofc.res. Hono copies those headers into the response thatc.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 typedVariablesmakec.get("session")a session manager, notunknown. - No session yet:
session.idstaysundefineduntilupdate()signs a first token. That's the check/memakes, 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 ofupdate(), 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. |
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 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:
defineJWESessionencrypts the token, so the user can't read it either. It takes anoctkey such asgenerateJWK("A256GCM"); see Configure a session. - API clients: set
sessionHeaderso 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. - 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.
- 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 recipe does.