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:

  • unjwt installed, as described in Install unjwt.
  • A runtime with the Fetch API's Request and Response: Node.js 22 or later, Bun, Deno or Cloudflare Workers.
  • For the first and last task, a key pair in the TOKEN_PRIVATE_JWK and TOKEN_PUBLIC_JWK environment variables; for the session task, a key in SESSION_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:

create-keys.ts
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:

api-token.ts
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 carries exp fifteen minutes out, and verify refuses it after that with ERR_JWT_EXPIRED. Short lifetimes keep a stolen token from being useful for long.
  • audience: the token names the API it's for in aud, and verify refuses one made for another service. A token without aud is refused too.
  • algorithms: the key already says ES256, 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:

encrypt-payload.ts
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 publicKey and decrypt with privateKey, the reverse of signing. Encrypting with the private half throws ERR_JWK_INVALID.
  • Algorithms from the key: ECDH-ES+A256KW is in the key's alg, and the content is encrypted with A256GCM unless you pass enc. decrypt accepts 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.

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:

cookie-session.ts
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.id is undefined, which is how /me tells a visitor from a signed-in user.
  • The cookie: update() writes __Host-unjwt-jws onto headers as HttpOnly; Secure; SameSite=Lax, valid for maxAge. A __Host- cookie needs HTTPS, or localhost while you develop.
  • res: { headers }: the session writes Set-Cookie into the headers you pass, so every response sends them. Without res, the session can read but update() 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:

handle-errors.ts
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_EXPIRED gets 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:

SituationWhat happens
TOKEN_PRIVATE_JWK, TOKEN_PUBLIC_JWK or SESSION_JWK unsetThe module throws when it loads, so the server fails to start.
Token expired, forged, garbled or for another audienceauthenticate throws a JWTError; listInvoices answers 401.
JWE sealed for another keydecrypt throws ERR_JWE_DECRYPTION_FAILED.
Session cookie signed with another keyThe session reads as empty, so /me answers 401. The bad cookie is dropped from the response.
Session opened without resupdate() throws ERR_SESSION_READONLY_EVENT.
App served over plain HTTP from a host other than localhostThe 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 defineJWESession and rolling, 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.