Concepts

The ideas every page here leans on: what a token is, signed versus encrypted, keys and key pairs, JWK Sets, algorithms, time claims, errors, sessions and limits.

You don't need a cryptography background to use unjwt. You do need a handful of words, because JOSE, the family of standards behind JSON Web Tokens, has a name for everything. This page explains each one once. Every other page links back here, so if a term somewhere feels unfamiliar, it's probably explained below.

#What a JWT is

A JSON Web Token (RFC 7519) is a short string that carries a few facts, such as "this is user user_1a2b, and this expires at noon". Those facts are the claims: a JSON object like { "sub": "user_1a2b", "exp": 1792982251 }. A few claim names are registered and mean the same thing everywhere: sub is who the token is about, iss who issued it, aud who it's for, exp, nbf and iat are times, and jti is the token's own ID. Anything else is yours to add.

Next to the claims sits the protected header, a small JSON object that says how the token was made: which algorithm (alg), which key (kid), and what kind of token it is (typ). A signed token is three parts, each base64url-encoded and joined by dots:

eyJraWQiOiIyMDI2LTEwIiwiYWxnIjoiRVMyNTYiLCJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyXzFhMmIifQ.p0Fy…
       protected header                                  claims               signature

Base64url is an encoding, not a lock. Anyone holding the string can decode the first two parts and read them.

#Signed is not secret

There are two ways to protect a token, and they answer different questions:

  • A JWS is a sealed letter. You can read it through the envelope, but there's a signature across the flap. Anyone with the public key can check that the letter is unchanged and that it came from whoever holds the private key (RFC 7515). Use it when the client may read the data and you need to trust it when it comes back: access tokens, ID tokens, signed links.
  • A JWE is a locked box. Only the recipient's key opens it, and nobody else learns what's inside (RFC 7516). Every algorithm here also detects tampering, so a changed byte fails to open. Use it when the client, or anything between you and the recipient, must not read the data.

"JWT" covers both: it's a JWS or a JWE whose payload is a claims object. The common mistake is putting secrets into a signed token because it looks scrambled. If the claims must stay private, encrypt. Sign and verify and Encrypt and decrypt cover each one.

#Keys and key pairs

A symmetric key, or secret, is one key that does both jobs: the same secret signs and verifies an HS256 token, or encrypts and decrypts an A256KW one. Everyone who can check the token can also make one, so a secret only works when one party, or a few that trust each other, does both.

A key pair is two keys, made together. The private key stays with you, the public key can go to anyone:

JobPrivate keyPublic key
Signed token (JWS)signsverifies
Encrypted token (JWE)decryptsencrypts

So an issuer signs with its private key and every API verifies with the public one, and a sender encrypts with the recipient's public key so only the recipient can decrypt. generateJWK hands you both halves as { privateKey, publicKey }; keep each one where it's used. Passing the wrong half throws ERR_JWK_INVALID. Generate keys shows every algorithm.

#JWK and the keyring

A JWK (RFC 7517) is a key written as JSON: kty names the family (oct for a secret, RSA, EC, OKP), alg the one algorithm it's for, and kid its name. Because it's plain JSON, you can store it in an environment variable or publish it. Import and export keys converts to and from a CryptoKey, raw bytes and PEM.

A JWK Set is the keyring: { "keys": [ … ] }. A server publishes its public keys as one, often at /.well-known/jwks.json, and keeps an old key on the ring for a while after it starts signing with a new one, so tokens already out there still verify. That's how you rotate keys.

The kid in a token's header is the label on the key that made it. When you verify against a JWK Set, kid picks which keys on the ring to try, and a kid that matches none is ERR_JWK_KEY_NOT_FOUND. A label narrows the search and never vouches for anything: anybody can write any kid into a header, and only the signature or the decryption decides. Use a JWK Set covers rotation and lookups.

#Algorithms come from the key

A JWK that carries alg decides the algorithm. sign and encrypt read it from the key, so you don't repeat it, and verify and decrypt accept only that algorithm. A token that claims another one is refused before any cryptography runs. That rule closes a whole family of attacks where a token picks its own, weaker algorithm.

A key that names no algorithm, such as raw bytes, needs it spelled out: alg when you sign or encrypt, and algorithms when you verify or decrypt. Even when the key carries alg, pinning algorithms: ["ES256"] on the verifying side is a cheap way to write down what you expect. Choose a signing algorithm and Choose encryption algorithms help you pick.

#Time claims and clocks

Three claims are times, written as whole seconds since 1970, not milliseconds:

  • exp: the token is refused from this moment on, with ERR_JWT_EXPIRED.
  • nbf: "not before", refused until this moment with ERR_JWT_NBF.
  • iat: when it was issued.

You rarely write them yourself. expiresIn: "15m" on sign or encrypt sets exp fifteen minutes from now and iat to now. On the verifying side, maxTokenAge: "1h" refuses a token whose iat is older than an hour, whatever its exp says. Durations are a number of seconds or a string such as "30s", "15m", "2h", "7D", and case matters: "5m" is five minutes, "5M" five months.

Clocks on two machines never agree exactly. clockTolerance: "30s" lets each time check be off by that much; it defaults to 0. An exp written in milliseconds is a date tens of thousands of years away and passes every check, so if you build claims by hand, divide Date.now() by 1000. Validate claims lists every check.

#Compact and JSON serialization

The dotted string above is the compact form: one signature, or one recipient, and what most people mean by "a JWT". A compact JWE has five parts instead of three. The JSON form is an object that can carry several signatures over one payload, or one ciphertext that several recipients can each open. sign, verify, encrypt and decrypt work on the compact form; Sign for several verifiers and Encrypt for several recipients cover the JSON one.

#Bad tokens and bad setup both throw

Every token that reaches your server came from someone you don't control, and every key and option came from you. unjwt treats both the same way: a forged signature, an expired token, a wrong audience, a key of the wrong type or a malformed option all throw a JWTError with a code. Nothing returns false, so a token can't slip through an if you forgot.

That makes the request handler the place to decide. Catch, narrow with isJWTError, and map the codes that mean "bad token" to a 401. Let everything else through, because that's a bug in your setup, and you want to hear about it. The Quickstart shows the pattern, and Handle errors lists every code.

#Sessions

A session is a JWT that keeps a signed-in user's data, carried in a cookie or a request header. It's stateless: the token holds the data, so there's no session table to look up, and any server with the key can read it. The flip side is that you can't take back one token before it expires without a list of your own; a hook that runs on every read is where you'd check it.

A session is lazy. Until you call update(), there's no token and id is undefined, which is how you tell a visitor from a signed-in user. update() mints the token and writes the cookie, clear() deletes it. Signed sessions (defineJWSSession) can be read by the client; encrypted ones (defineJWESession) can't. Sessions covers both.

#Limits that fail closed

A token is input, and reading it costs work: checking a signature, trying keys, running a password-based key derivation. Every call that reads a token caps that work, and the defaults are generous for real traffic:

LimitDefaultPast it
Signatures in one JSON JWS16ERR_JWS_INVALID
Recipients in one JSON JWE16ERR_JWE_INVALID
Matching keys tried from a JWK Set8ERR_JWK_KEY_NOT_FOUND
Key trials across one multi-signature or multi-recipient call16ERR_JWK_KEY_NOT_FOUND
Password-based key derivation iterations per call2 400 000ERR_JWE_INVALID

Past a limit the token is refused. The library never checks the first few and lets the rest through. Limits shows how to raise one for a call that needs it.