Generate keys
Make a fresh secret or key pair for any signing or encryption algorithm, name it, and store it so it survives a restart.
generateJWK(alg) makes a new key for one algorithm and hands it back as JSON. For a symmetric algorithm such as HS256 that's one secret; for an asymmetric one such as ES256 it's a key pair, two JWKs you keep apart: the private key stays on your server, the public key goes to whoever verifies or encrypts. If you're unsure which algorithm to pick, Choose a signing algorithm and Choose encryption algorithms help.
#Before you start
- Pick the algorithm first. A key is made for one algorithm and carries it as
alg; a key forES256never signsES384tokens. - Generate a key once, outside the request path, and store it. A key generated at start-up is gone on the next restart, and so is every token signed with it.
- Have a place for the private key or secret: a secret manager or an environment variable that is never logged or committed. The public key is not secret.
#Generate a key pair
Pass an asymmetric algorithm and you get both halves back:
import { generateJWK } from "unjwt/jwk";
const { privateKey, publicKey } = await generateJWK("ES256");
// privateKey: { kty: "EC", x: "cbCcIXJK…", y: "bcMypp7p…", crv: "P-256", d: "CU4reulc…", alg: "ES256", kid: "OC-A6_UJ…" }
// publicKey: { kty: "EC", x: "cbCcIXJK…", y: "bcMypp7p…", crv: "P-256", alg: "ES256", kid: "OC-A6_UJ…" }- Two keys:
privateKeygoes tosign()ordecrypt(),publicKeytoverify()orencrypt(). Keep both; don't strip members off the private key to make a public one. - One name: both halves carry the same
kid, so a token signed with the private key finds its public key in a JWK Set. - No usage members: the JWKs carry no
extorkey_ops. Whoever imports one gets the operations itsalgallows.
#Generate a secret
A symmetric algorithm gives you a single oct JWK, with the secret in k:
const secret = await generateJWK("HS256");
// { kty: "oct", k: "snzJtoKE…", alg: "HS256", kid: "z2YTfa4L…" }The same holds for the encryption secrets: A256KW and A256GCMKW for wrapping keys, A256GCM or A256CBC-HS512 for a key you encrypt with directly (dir). Anyone holding a secret can both sign and verify with it, so share it only with services you'd trust to issue tokens.
| Algorithm | generateJWK(alg) returns |
|---|---|
HS*, A*KW, A*GCMKW, A*GCM, A*CBC-HS* | one oct JWK |
RS*, PS*, RSA-OAEP* | { privateKey, publicKey }, kty: "RSA" |
ES* | { privateKey, publicKey }, kty: "EC" |
Ed25519, EdDSA | { privateKey, publicKey }, kty: "OKP" |
ECDH-ES* | { privateKey, publicKey }, kty: "EC", or "OKP" for X25519 |
PBES2-* has no generated key: a password-based key comes from Derive keys from a password. dir and none are not key algorithms either.
#Name the key
A kid is the name a token carries in its header, so a verifier holding several keys knows which one to try. When you don't pass one, the key is named by its RFC 7638 thumbprint, a digest of its public members: two different keys never share it, and both halves of a pair get the same one. Pass a string when you'd rather read the name, or false for none:
await generateJWK("ES256", { kid: "2026-10" }); // both halves: kid "2026-10"
await generateJWK("HS256", { kid: false }); // no kid member at allsign() and encrypt() copy the key's kid into the token's protected header. A name is a label, not proof: a verifier still checks the signature against the key it picked.
#Store the key and load it at start-up
Generate the key once, from a script or a REPL, and put the JSON of each half where it belongs:
const { privateKey, publicKey } = await generateJWK("ES256", { kid: "2026-10" });
JSON.stringify(privateKey); // into your secret manager, as SIGNING_KEY
JSON.stringify(publicKey); // safe to publish, for verifiersYour app then reads the private key once, when it starts:
import { importKey, type JWK_EC_Private } from "unjwt/jwk";
const raw = process.env.SIGNING_KEY;
if (!raw) throw new Error("SIGNING_KEY is not set");
/** The private half, for `sign()`. Never log it or send it anywhere. */
export const signingKey: JWK_EC_Private<"ES256"> = JSON.parse(raw);
// Fails at start-up, not on the first request, when the variable holds the wrong key.
await importKey(signingKey, { alg: "ES256", expect: "private" });- Fail at start-up: a missing variable stops the process before it serves anything, instead of failing the first login.
- Check the key early:
importKeywithexpect: "private"refuses a public key pasted by mistake, andalg: "ES256"a key made for another algorithm. Both throwERR_JWK_INVALID. - The type:
JWK_EC_Private<"ES256">letssign()accept the parsed JSON without a cast.
#Keep a private key inside the process
generateKey takes the same algorithm and returns Web Crypto objects instead of JSON. With extractable: false, the private key can sign but its material can never be read back out, so a compromised process can use it but cannot copy it:
import { generateKey } from "unjwt/jwk";
const { privateKey, publicKey } = await generateKey("ES256", { extractable: false });
privateKey.extractable; // false
publicKey.extractable; // true: a public key is always exportableSuch a key lives only as long as the process, so this fits keys you can afford to lose on a restart, such as a short-lived signing key whose public half you publish while it runs. generateKey(alg, { toJWK: true }) returns JWKs like generateJWK.
#Restrict what a key may do
keyUsage narrows the operations, and the JWKs then carry what each half keeps as key_ops:
const { privateKey, publicKey } = await generateJWK("ES256", { keyUsage: ["sign", "verify"] });
privateKey.key_ops; // ["sign"]
publicKey.key_ops; // ["verify"]A list that leaves one half with nothing throws: keyUsage: ["sign"] on ES256 would publish a public key no verifier accepts. Other metadata such as use: "sig" or x5c is merged onto both halves as given.
#When it fails
| Situation | What happens |
|---|---|
alg is PBES2-*, dir, none or unknown | Throws ERR_JWK_UNSUPPORTED. |
EdDSA with a curve other than Ed25519, ECDH-ES* with a curve it does not support | Throws ERR_JWK_UNSUPPORTED. |
namedCurve contradicts the algorithm (P-384 for ES256) | Throws ERR_INVALID_OPTION. |
modulusLength below 2048, or a publicExponent that is not non-empty bytes | Throws ERR_INVALID_OPTION. |
keyUsage names an operation the algorithm can't do, or empties one half of the pair | Throws ERR_INVALID_OPTION, naming the missing usage. |
kid is neither a string nor false | Throws ERR_INVALID_OPTION. |
Metadata sets alg, kty, key_ops, ext or a key member such as d | Throws ERR_INVALID_OPTION, naming the members. |
Handle errors lists every code.
#Options
generateJWK(alg, options) and generateKey(alg, options):
| Option | Default | Notes |
|---|---|---|
kid | the RFC 7638 thumbprint | A string is used as given, false sets none. generateKey reads it only with toJWK: true. |
modulusLength | 2048 | RSA only, at least 2048 (RFC 7518 §3.3). |
publicExponent | 0x010001 | RSA only, as big-endian bytes. |
namedCurve | P-256 for EC | ES256/ES384/ES512 and Ed25519 fix their curve. ECDH-ES* picks from P-256, P-384, P-521, X25519. |
keyUsage | every usage alg allows | Narrows the usages and writes key_ops on the JWKs. |
use, x5c, x5t, x5t#S256, x5u | none | generateJWK only. Merged onto the key, both halves of a pair. |
toJWK | false | generateKey only. Return JWKs instead of CryptoKey, CryptoKeyPair or bytes. |
extractable | true | generateKey only. Ignored with toJWK, which has to export the key. |
generateKey without toJWK returns a CryptoKey for HS*, A*KW, A*GCM and A*GCMKW, a CryptoKeyPair for the asymmetric algorithms, and a Uint8Array for A*CBC-HS*, which has no Web Crypto key type. The return types follow the algorithm you pass, so no cast is needed.
#Going further
- Publish the public halves and rotate: Use a JWK Set.
- Only the private key stored: derive the public half at start-up.
- Keys from OpenSSL or a cloud console: Use PEM keys.
- Keys for sessions: Configure a session says which kind of key each session family takes.