Sign a token
Turn a payload and a signing key into a compact JWS, with the algorithm, kid, typ and time claims filled in for you.
sign(payload, key, options) takes your claims, signs them with a key and returns one URL-safe string you can put in an Authorization header or a cookie. A key from generateJWK already knows its algorithm and its kid, so most calls need only the payload, the key and an expiry. The token stays readable by anyone who holds it: signing proves who issued it, it doesn't hide it.
#Before you start
- A signing key. For one service that signs and checks its own tokens, a shared secret (
generateJWK("HS256")) is enough. When other services verify, use a key pair (generateJWK("ES256")): the private key signs, and the public key you hand out only verifies. Choose a signing algorithm helps you pick. - A key that survives restarts: generate it once, store the JWK as JSON in your secret store, and load it at start-up. A key generated at boot invalidates every token on the next deploy.
- An HMAC secret at least as long as its hash: 32 bytes for
HS256, 48 forHS384, 64 forHS512. RSA keys need a modulus of 2048 bits or more. - Nothing private in the payload. Anyone can decode it.
#Sign an access token
An issuer loads its private key once and signs a short-lived token per request:
import { sign } from "unjwt/jws";
import type { JWSSignJWK } from "unjwt/jws";
import { isPrivateJWK } from "unjwt/utils";
const raw = process.env.TOKEN_SIGNING_KEY;
if (!raw) throw new Error("TOKEN_SIGNING_KEY is not set");
const signingKey: JWSSignJWK = JSON.parse(raw);
if (!isPrivateJWK(signingKey)) throw new Error("TOKEN_SIGNING_KEY must be a private JWK");
/** A 15-minute access token for `api.example.com`, signed with the issuer's private key. */
export function issueAccessToken(userId: string, scope: string[]) {
return sign(
{
iss: "https://auth.example.com",
aud: "https://api.example.com",
sub: userId,
scope: scope.join(" "),
},
signingKey,
{ expiresIn: "15m", protectedHeader: { typ: "at+jwt" } },
);
}- The key from the environment:
TOKEN_SIGNING_KEYholds the private JWK as JSON. The module stops at start-up when it's missing, or when someone stored the public half by mistake, instead of failing on the first login. - No
algoption: the algorithm comes from the key'salgmember, and itskidgoes into the header so verifiers can pick the right public key from a JWK Set. expiresIn: "15m": writesexpfifteen minutes from now, andiatalong with it.typ: "at+jwt": marks the token as an access token (RFC 9068), so a verifier can refuse other kinds of token signed by the same key.
The token decodes to this header and payload:
// header: { kid: "2026-10", typ: "at+jwt", alg: "ES256" }
// payload: { iss: "https://auth.example.com", aud: "https://api.example.com",
// sub: "user_1a2b", scope: "invoices:read", iat: 1793005200, exp: 1793006100 }#Choose what to sign
The payload can be an object, a string or bytes. The type decides what sign adds:
| Payload | Signed as | typ added | Time options |
|---|---|---|---|
| An object | its JSON text | "JWT" | written into it |
| A string | its UTF-8 bytes | no | throw ERR_INVALID_OPTION |
A Uint8Array | the bytes, as given | no | throw ERR_INVALID_OPTION |
An object JSON.stringify can't serialize, such as one holding a BigInt, throws ERR_INVALID_OPTION. A string or bytes payload is for signing something that isn't a set of claims: a webhook body, a document hash. The verifier then reads it with payload: "string" or "bytes" (Verify a token).
#Pass the key
- A JWK from
generateJWKor Import and export keys.algandkidcome from the key. An EC or Ed25519 JWK withoutalg, such as one exported from aCryptoKey, signs with the algorithm its curve names:ES256for P-256,ES384for P-384,ES512for P-521,EdDSAfor Ed25519. An RSA oroctJWK withoutalgfits several algorithms, so passalg. An asymmetric JWK must be the private half: a public one throwsERR_JWK_INVALID. - A
CryptoKey. Passalg. Nokidis written, so set one inprotectedHeaderwhen verifiers select keys by it. - Raw bytes, a
Uint8Array, as an HMAC secret. Pass anHS*alg.
A string is never a key, so a PEM file or a password passed by mistake is refused with ERR_JWK_INVALID; import PEM text with importPEM first. A JWK Set isn't a signing key either: pick the entry you sign with.
await sign({ sub: "user_1a2b" }, secretBytes, { alg: "HS256" });
// header: { alg: "HS256", typ: "JWT" }
await sign({ sub: "user_1a2b" }, new Uint8Array(16), { alg: "HS256" });
// JWTError ERR_JWK_INVALID: HS256 requires a key of at least 32 bytes (got 16)A key declared for one algorithm signs with that one only: sign(payload, es384Key, { alg: "ES256" }) throws ERR_JWK_INVALID.
#Set the expiry and other time claims
The time options write exp, nbf and iat into an object payload:
await sign({ sub: "user_1a2b" }, key, {
currentDate: new Date("2026-10-26T09:00:00Z"),
expiresIn: "1h",
notBeforeIn: 0,
});
// payload: { sub: "user_1a2b", iat: 1793005200, exp: 1793008800, nbf: 1793005200 }- A claim already in the payload wins.
sign({ sub: "user_1a2b", exp: 1800000000 }, key, { expiresIn: "1h" })keeps thatexpand, since nothing else was written, adds noiateither. iatcomes along whenever an option writesexpornbf, and on its own withissuedAt: true.- Durations are seconds as a number, or strings like
"30s","15m","2h","7D","1W","3M","1Y"(long forms such as"7days"work too). A malformed one throwsERR_INVALID_OPTION. - Whole seconds, rounded down, as JWT time claims are (RFC 7519 §2).
- String and bytes payloads have no claims to write into:
expiresIn,expiresAt,notBeforeIn,notBeforeAtorissuedAtwith one throwsERR_INVALID_OPTION.
Validate claims covers how the verifier checks them.
#Add header members
protectedHeader adds members to the signed header. The header is built in this order, later steps winning: the key's kid, then your protectedHeader, then alg. You can't set alg there.
typdefaults to"JWT"for an object payload. Atypyou set is kept and must be a string.ctyis never added. Setcty: "JWT"when the payload is itself a token (RFC 7519 §5.2).critlists extensions the verifier must understand or refuse the token. It must be a non-empty array of strings, may not name a registered member such askidortyp, and every entry must be a member of the header you're building; otherwiseERR_INVALID_OPTION.jwk, when you embed a key, must be a public JWK.
#Leave the payload unencoded
b64: false (RFC 7797) puts the payload in the token as plain text instead of base64url. sign adds "b64" to crit for you, as the RFC requires:
await sign("amount=1200¤cy=EUR", key, { protectedHeader: { b64: false } });
// "eyJraWQiOi….amount=1200¤cy=EUR.cyCgwIp5…"
// header: { kid: "2026-10", b64: false, alg: "HS256", crit: ["b64"] }The payload must be valid UTF-8 and, in a compact token, contain no .. Sign for several verifiers has a JSON form without that limit.
#What you get back
A string of three base64url segments joined by dots: protected header, payload, signature (RFC 7515 §7.1). For several signatures on one payload, use signMulti.
#When it fails
| Situation | What happens |
|---|---|
No alg option, and the key names none: a CryptoKey, raw bytes, or an RSA or oct JWK without alg | Throws ERR_JWS_ALG_MISSING. |
alg is "none" or not a supported algorithm | Throws ERR_JWS_ALG_NOT_ALLOWED. |
The key is a string, a public key, too short, an RSA key under 2048 bits, or made for another alg | Throws ERR_JWK_INVALID. |
Both expiresIn and expiresAt, both notBeforeIn and notBeforeAt, or a negative notBeforeIn | Throws ERR_JWT_CLAIM_INVALID. |
The payload holds a cnf.jwk that is not a public JWK | Throws ERR_JWT_CLAIM_INVALID. |
A malformed duration or Date, a header or payload JSON can't carry, a bad crit, typ, b64 or jwk | Throws ERR_INVALID_OPTION. |
| A time option with a string or bytes payload | Throws ERR_INVALID_OPTION. |
b64: false with a payload that contains . or is not UTF-8 | Throws ERR_JWS_INVALID. |
Handle errors lists every code and what to do about it.
#Options
| Option | Default | Notes |
|---|---|---|
alg | the JWK's alg, else the one an EC or Ed25519 JWK's curve names | Required for a CryptoKey, raw bytes, or an RSA or oct JWK without alg. |
protectedHeader | none | Extra signed header members: kid, typ, cty, crit, b64, jwk, your own. |
expiresIn | none | exp as currentDate plus a duration. Exclusive with expiresAt. |
expiresAt | none | exp at that Date. |
notBeforeIn | none | nbf as currentDate plus a duration; 0 is now. Exclusive with notBeforeAt. |
notBeforeAt | none | nbf at that Date. |
issuedAt | none | true writes iat as currentDate, a Date writes that instant. Doesn't move exp. |
currentDate | now | The clock: iat when written, and the start of expiresIn and notBeforeIn. |
#Going further
- The receiving side: Verify a token.
- Rotating signing keys: sign with the newest key and publish every key still in use as a JWK Set.
- Private claims: encrypt the signed token so only the recipient can read it.
- Sessions in cookies: Sessions sign, refresh and clear the token for you.