JWT
Sign and verify JWTs with @senrijs/senri/jwt
import { } from "@senrijs/senri";
import { , , type } from "@senrijs/senri/jwt";
declare const : { : string };
const = <>();
.("/login", async () => ({
: await ({ : "42" }, ., { : "HS256", : 3600 }),
}));
.("/api", ({ : ., : ["HS256"] })); // Authorization: Bearer <token>
.("/api/me", (, ) => ({ : .("jwtPayload") }));It uses only Web Crypto, and runs on Bun, Deno, Node.js, Cloudflare Workers and the browser.
Rules
algorithmsis required. A token is verified only when itsalgis in it.noneis never acceptedexpandnbfare checked when present (clockToleranceallows for clock skew).issuer,audience,subjectandmaxAgecan also be set- To always set an expiry, use
expiresIninsignJwt() - To read the token from a cookie, write
jwt({ cookie: "name", ... }) - An invalid token is a
JwtError(a 401HttpError) withWWW-Authenticate: Bearer error="invalid_token".err.reasontells why (expired,signatureand so on)
Algorithms and keys
| Algorithms | Keys |
|---|---|
| HS256, HS384, HS512 | A string secret (32 bytes or more for HS256, 48 for HS384, 64 for HS512; shorter is a TypeError) |
| RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, EdDSA, Ed25519 | PEM (PUBLIC KEY / PRIVATE KEY), JWK or CryptoKey |
- A PEM public key is never used as an HMAC secret (this prevents algorithm confusion attacks)
- ES512 is not supported yet
Key rotation
.("/api", ({
: [{ : "2026-11", : }, { : "2026-10", : }],
: ["HS256"],
}));signJwt() puts kid in the header, and verifyJwt() tries only the key with the token's kid (and keys without a kid). The keys of a JWKS can be passed as is.
Fetching keys from a remote JWKS URL and encryption (JWE) are not supported.
Options
Prop
Type