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 for HS384, 64 for HS512. 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:

sign-api-token.ts
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_KEY holds 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 alg option: the algorithm comes from the key's alg member, and its kid goes into the header so verifiers can pick the right public key from a JWK Set.
  • expiresIn: "15m": writes exp fifteen minutes from now, and iat along 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:

PayloadSigned astyp addedTime options
An objectits JSON text"JWT"written into it
A stringits UTF-8 bytesnothrow ERR_INVALID_OPTION
A Uint8Arraythe bytes, as givennothrow 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 generateJWK or Import and export keys. alg and kid come from the key. An EC or Ed25519 JWK without alg, such as one exported from a CryptoKey, signs with the algorithm its curve names: ES256 for P-256, ES384 for P-384, ES512 for P-521, EdDSA for Ed25519. An RSA or oct JWK without alg fits several algorithms, so pass alg. An asymmetric JWK must be the private half: a public one throws ERR_JWK_INVALID.
  • A CryptoKey. Pass alg. No kid is written, so set one in protectedHeader when verifiers select keys by it.
  • Raw bytes, a Uint8Array, as an HMAC secret. Pass an HS* 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 that exp and, since nothing else was written, adds no iat either.
  • iat comes along whenever an option writes exp or nbf, and on its own with issuedAt: 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 throws ERR_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, notBeforeAt or issuedAt with one throws ERR_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.

  • typ defaults to "JWT" for an object payload. A typ you set is kept and must be a string.
  • cty is never added. Set cty: "JWT" when the payload is itself a token (RFC 7519 §5.2).
  • crit lists 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 as kid or typ, and every entry must be a member of the header you're building; otherwise ERR_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&currency=EUR", key, { protectedHeader: { b64: false } });
// "eyJraWQiOi….amount=1200&currency=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

SituationWhat happens
No alg option, and the key names none: a CryptoKey, raw bytes, or an RSA or oct JWK without algThrows ERR_JWS_ALG_MISSING.
alg is "none" or not a supported algorithmThrows 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 algThrows ERR_JWK_INVALID.
Both expiresIn and expiresAt, both notBeforeIn and notBeforeAt, or a negative notBeforeInThrows ERR_JWT_CLAIM_INVALID.
The payload holds a cnf.jwk that is not a public JWKThrows ERR_JWT_CLAIM_INVALID.
A malformed duration or Date, a header or payload JSON can't carry, a bad crit, typ, b64 or jwkThrows ERR_INVALID_OPTION.
A time option with a string or bytes payloadThrows ERR_INVALID_OPTION.
b64: false with a payload that contains . or is not UTF-8Throws ERR_JWS_INVALID.

Handle errors lists every code and what to do about it.

#Options

OptionDefaultNotes
algthe JWK's alg, else the one an EC or Ed25519 JWK's curve namesRequired for a CryptoKey, raw bytes, or an RSA or oct JWK without alg.
protectedHeadernoneExtra signed header members: kid, typ, cty, crit, b64, jwk, your own.
expiresInnoneexp as currentDate plus a duration. Exclusive with expiresAt.
expiresAtnoneexp at that Date.
notBeforeInnonenbf as currentDate plus a duration; 0 is now. Exclusive with notBeforeAt.
notBeforeAtnonenbf at that Date.
issuedAtnonetrue writes iat as currentDate, a Date writes that instant. Doesn't move exp.
currentDatenowThe 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.