Quickstart
Four tasks with unjwt: issue and check an API token, encrypt a payload for one recipient, keep a cookie session, and answer a failed token.
Each task below is a small module you can drop into a server and call from a route handler, and each ends with a link to the page that tells the rest of its story. If a word like "key pair" or "claims" is new, Concepts explains it in a minute.
#Before you start
You need three things in place:
unjwtinstalled, as described in Install unjwt.- A runtime with the Fetch API's
RequestandResponse: Node.js 22 or later, Bun, Deno or Cloudflare Workers. - For the first and last task, a key pair in the
TOKEN_PRIVATE_JWKandTOKEN_PUBLIC_JWKenvironment variables; for the session task, a key inSESSION_JWK. The tasks show how to make them.
#Issue and check an API token
An API token is a sealed letter: your auth service signs it with its private key, and the API checks the signature with the public one. Make the key pair once, then copy each string into your secret store as an environment variable:
import { generateJWK } from "unjwt/jwk";
const { privateKey, publicKey } = await generateJWK("ES256", { kid: "2026-10" });
export const env: Record<string, string> = {
TOKEN_PRIVATE_JWK: JSON.stringify(privateKey), // only where tokens are issued
TOKEN_PUBLIC_JWK: JSON.stringify(publicKey), // wherever tokens are verified
};Then one module issues a token for a client and checks the one that comes back with a request:
import { sign, verify } from "unjwt/jws";
import type { JWSSignJWK, JWSVerifyJWK } from "unjwt";
function jwkFromEnv(name: string) {
const json = process.env[name];
if (!json) throw new Error(`${name} is not set`);
return JSON.parse(json);
}
const privateKey: JWSSignJWK = jwkFromEnv("TOKEN_PRIVATE_JWK");
const publicKey: JWSVerifyJWK = jwkFromEnv("TOKEN_PUBLIC_JWK");
const AUDIENCE = "https://api.example.com";
/** A token that lets `clientId` call the API for the next 15 minutes. */
export async function issueToken(clientId: string, scope: string) {
return sign({ sub: clientId, aud: AUDIENCE, scope }, privateKey, { expiresIn: "15m" });
}
/** The claims of the request's bearer token; throws a `JWTError` when the token is bad. */
export async function authenticate(request: Request) {
const header = request.headers.get("authorization") ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
const { payload } = await verify(token, publicKey, {
algorithms: ["ES256"],
audience: AUDIENCE,
});
return payload;
}Each choice in the code guards against one way a token can be misused:
- Two halves: only the service that issues tokens needs
TOKEN_PRIVATE_JWK. An API that only verifies gets the public half, so a leak there can't mint tokens. expiresIn: the token carriesexpfifteen minutes out, andverifyrefuses it after that withERR_JWT_EXPIRED. Short lifetimes keep a stolen token from being useful for long.audience: the token names the API it's for inaud, andverifyrefuses one made for another service. A token withoutaudis refused too.algorithms: the key already saysES256, and pinning it on the verifying side writes down what you expect.- Start-up check: a missing variable stops the module from loading, so a forgotten key breaks the deploy, not the first request.
Sign a token and Verify a token cover every option, and Use a JWK Set shows how to rotate the key without breaking tokens already out there.
#Encrypt a payload for one recipient
A JWE is a locked box: you lock it with the recipient's public key, and only their private key opens it. Here a shop sends invoice details to a billing service, and nothing on the way can read the bank details:
import { decrypt, encrypt } from "unjwt/jwe";
import { generateJWK } from "unjwt/jwk";
// The billing service makes its key pair once and hands out the public half
const billing = await generateJWK("ECDH-ES+A256KW", { kid: "billing-2026-10" });
/** Sender side: only the holder of the private half can open the result. */
export async function sealInvoice(invoice: { id: string; iban: string }) {
return encrypt(invoice, billing.publicKey, { expiresIn: "1h" });
}
/** Billing side: the invoice, or a `JWTError` when the token was not sealed for this key. */
export async function openInvoice(token: string) {
const { payload } = await decrypt(token, billing.privateKey);
return payload;
}Two details matter here:
- Which half: you encrypt with
publicKeyand decrypt withprivateKey, the reverse of signing. Encrypting with the private half throwsERR_JWK_INVALID. - Algorithms from the key:
ECDH-ES+A256KWis in the key'salg, and the content is encrypted withA256GCMunless you passenc.decryptaccepts only what the key names.
In a real deployment the billing service generates its pair once, keeps the private half in its environment and hands the public half, or a JWK Set of them, to every sender. Encrypt a payload and Decrypt a token go further.
#Keep a cookie session
A session keeps a signed-in user in a cookie, as a token only your server can mint. defineJWSSession runs once at start-up, and use() gives you the session of each request. This handler works on a Web Request, the way Bun, Deno and Workers hand you one:
import { defineJWSSession } from "unjwt/session";
import type { JWK_oct } from "unjwt";
const json = process.env.SESSION_JWK;
if (!json) throw new Error("SESSION_JWK is not set");
const key: JWK_oct<"HS256"> = JSON.parse(json);
const appSession = defineJWSSession<{ user: string }>({ key, maxAge: "7D" });
export async function handle(request: Request) {
const headers = new Headers();
const session = await appSession.use({ req: request, res: { headers } });
const { pathname } = new URL(request.url);
if (request.method === "POST" && pathname === "/login") {
// Check the credentials against your user store first
await session.update({ user });
return Response.json({ user }, { headers });
}
if (pathname === "/me") {
if (!session.id) return Response.json({ error: "Not signed in" }, { status: 401, headers });
return Response.json({ user: session.data.user }, { headers });
}
if (request.method === "POST" && pathname === "/logout") {
await session.clear();
return new Response(null, { status: 204, headers });
}
return new Response("Not found", { status: 404, headers });
}Make SESSION_JWK once with JSON.stringify(await generateJWK("HS256")), from unjwt/jwk. The handler then behaves like this:
- Lazy session: before
update(),session.idisundefined, which is how/metells a visitor from a signed-in user. - The cookie:
update()writes__Host-unjwt-jwsontoheadersasHttpOnly; Secure; SameSite=Lax, valid formaxAge. A__Host-cookie needs HTTPS, orlocalhostwhile you develop. res: { headers }: the session writesSet-Cookieinto the headers you pass, so every response sends them. Withoutres, the session can read butupdate()throws.- Signed, not secret: the client can decode the claims. Keep secrets out of a signed session, or switch to
defineJWESession.
Sessions explains the cookie, the header and the token in hand; Read, update and clear covers the manager, and the recipes show the same session on h3, Nitro, Nuxt and Hono.
#Handle a failed token
A bad token throws, and the handler decides what that means. The codes that say "this client sent a bad token" become a 401; anything else is a mistake in your setup and goes on to your error handler:
import { isJWTError } from "unjwt/error";
import type { JWTClaims } from "unjwt";
import { authenticate } from "./api-token.ts";
export async function listInvoices(request: Request) {
let claims: JWTClaims;
try {
claims = await authenticate(request);
} catch (error) {
if (isJWTError(error, "ERR_JWT_EXPIRED")) {
return unauthorized('error="invalid_token", error_description="expired"');
}
if (isJWTError(error) && REJECTED.has(error.code)) {
return unauthorized('error="invalid_token"');
}
throw error;
}
return Response.json({ client: claims.sub, invoices: [] });
}
// Codes that mean the client sent a bad token, not that your setup is wrong
const REJECTED = new Set<string>([
"ERR_JWS_INVALID",
"ERR_JWS_SIGNATURE_INVALID",
"ERR_JWS_ALG_NOT_ALLOWED",
"ERR_JWK_KEY_NOT_FOUND",
"ERR_JWT_NBF",
"ERR_JWT_CLAIM_INVALID",
"ERR_JWT_CLAIM_MISSING",
]);
function unauthorized(challenge: string): Response {
return new Response(null, {
status: 401,
headers: { "www-authenticate": `Bearer ${challenge}` },
});
}The catch sorts errors into three kinds:
- Expired:
ERR_JWT_EXPIREDgets its own description, so the client knows to fetch a new token rather than give up. - Rejected: a forged signature (
ERR_JWS_SIGNATURE_INVALID), a garbled or missing token (ERR_JWS_INVALID), a token for another audience (ERR_JWT_CLAIM_INVALID) and the rest of the set all get the same 401, so a client probing the API learns nothing more. - Everything else: rethrown. A key that fails to load or an option out of range is your bug, and a 401 would hide it.
Messages are for logs and may change between releases, so always branch on code. Handle errors lists every code.
#When it fails
Here's what each task does when something goes wrong:
| Situation | What happens |
|---|---|
TOKEN_PRIVATE_JWK, TOKEN_PUBLIC_JWK or SESSION_JWK unset | The module throws when it loads, so the server fails to start. |
| Token expired, forged, garbled or for another audience | authenticate throws a JWTError; listInvoices answers 401. |
| JWE sealed for another key | decrypt throws ERR_JWE_DECRYPTION_FAILED. |
| Session cookie signed with another key | The session reads as empty, so /me answers 401. The bad cookie is dropped from the response. |
Session opened without res | update() throws ERR_SESSION_READONLY_EVENT. |
App served over plain HTTP from a host other than localhost | The browser drops the __Host- cookie, so the user never stays signed in. |
#Going further
Once these four work, these pages take you further:
- Whole features: Recipes put the pieces together on a framework.
- Encrypted sessions and rotation: Configure a session covers
defineJWESessionandrolling, and Rotate keys replaces the session key without signing anyone out. - Proof of possession: DPoP proofs bind a token to the client's own key, so a stolen token alone is useless.