Migrate from 0.7 to 0.8
Update code written for unjwt 0.7.x so it runs on 0.8: declared payload modes, keys instead of strings, options objects, stricter sessions and stricter token checks.
0.8 is a breaking release, and most of its changes make the library refuse things 0.7 let through. Work through the sections that name a function or option you call; anything not listed behaves as it did. Going on to 0.9 afterwards, Migrate from 0.8 to 0.9 picks up where this page ends, and a few edits here point there instead.
#Before you start
Three things are worth knowing before you bump the version:
- Sessions sign out once: 0.8 reads only session tokens with
typ: "session+jwt", so every cookie 0.7 issued is refused once and the user signs in again. - Strings are no longer keys: if you sign with a string secret, you need a JWK or bytes first. That edit touches every call that takes a key.
- Tests: assertions on error messages need rewriting, because every error is a
JWTErrorand you branch on itscode.
#1. Declare the payload mode
0.7 looked at the payload and decided: JSON came back parsed, anything else came back as text. In 0.8 you say what you expect with payload, and the default "json" must be a JSON object:
// 0.7
const { payload } = await verify(token, key, { forceUint8Array: true });
const { payload: text } = await verify(textToken, key);
// 0.8 and later
const { payload } = await verify(token, key, { payload: "bytes" });
const { payload: text } = await verify(textToken, key, { payload: "string" });A text token read with the default mode throws ERR_JWS_INVALID (ERR_JWE_INVALID for decrypt). forceUint8Array is gone in 0.9, so write payload now.
#2. Turn string secrets into keys
0.7 turned a string key into HMAC secret bytes. In 0.8 a string is accepted only as a PBES2 password for encrypt and decrypt; everywhere else it throws ERR_JWK_INVALID:
// 0.7
await sign(claims, "my-secret", { alg: "HS256" });
// 0.8 and later: a JWK, or a Uint8Array with the algorithm named
const key = await generateJWK("HS256");
await sign(claims, key);
await sign(claims, secretBytes, { alg: "HS256" });
await verify(token, secretBytes, { algorithms: ["HS256"] });PEM text goes through importPEM, and a password that has to become a key goes through deriveJWKFromPassword.
#3. Name raw keys' algorithms
A JWK's alg is binding: a key with alg: "A256KW" only wraps keys, and asking it for anything else is ERR_JWK_INVALID. Raw Uint8Array keys are never guessed, so they need algorithms on the reading side:
// 0.7
await verify(token, secretBytes);
await decrypt(jwe, cekBytes);
// 0.8 and later
await verify(token, secretBytes, { algorithms: ["HS256"] });
await decrypt(jwe, cekBytes, { algorithms: ["dir"], encryptionAlgorithms: ["A256GCM"] });Without them, a raw key throws ERR_JWS_ALG_NOT_ALLOWED or ERR_JWE_ALG_NOT_ALLOWED.
#4. Pass key-management options as an object
wrapKey, unwrapKey and the password functions take their subject first and the algorithm in the options:
// 0.7
await wrapKey("A256KW", cek, kek);
await unwrapKey("A256KW", encryptedKey, kek, { format: "raw" });
await deriveJWKFromPassword(password, "PBES2-HS256+A128KW", { salt, iterations });
// 0.8 and later
await wrapKey(cek, kek, { alg: "A256KW" });
await unwrapKey(encryptedKey, kek, { alg: "A256KW", format: "raw" });
await deriveJWKFromPassword(password, { alg: "PBES2-HS256+A128KW", salt, iterations });deriveKeyFromPassword changes the same way. Four older aliases are gone too:
| 0.7 | 0.8 and later |
|---|---|
getJWKFromSet(jwks, kid) | getJWKsFromSet(jwks, (key) => key.kid === kid)[0] |
importFromPEM(pem, pemType, alg, options) | importPEM(pem, alg, { pemType, ...options }) |
exportToPEM(jwk, pemFormat, alg) | exportPEM(jwk, { pemFormat, alg }) |
computeExpiresInSeconds, computeMaxTokenAgeSeconds | computeDurationInSeconds |
#5. Expect thumbprints as key IDs
generateJWK and deriveJWKFromPassword name a key by its RFC 7638 thumbprint, 43 characters of base64url, where 0.7 used a random UUID. Both halves of a pair share it. A JWK you stored keeps the kid it has; pass kid: "2026-10" for a name of your own, or kid: false for none. Generate keys has the details.
#6. Give sessions key material and a lifetime
A session key must be a JWK or a CryptoKey; a string throws ERR_SESSION_KEY_INVALID. Derive a key once from your secret at start-up:
// 0.7
useJWESession(event, { key: process.env.SESSION_SECRET });
// 0.8
const key = await deriveJWKFromPassword(process.env.SESSION_SECRET, {
alg: "PBES2-HS256+A128KW",
salt: "app-session-salt",
iterations: 600_000,
});
useJWESession(event, { key });The per-call functions such as useJWESession are gone in 0.9, and so is a key pair as a JWE session key; the same key goes into defineJWESession from unjwt/session there.
jti, iat, exp and nbf belong to the session. They're dropped from the data you pass to update(), so an exp in the data no longer sets the lifetime. Set it with maxAge on the config, or per token:
// 0.7
await session.update({ userId, exp: Math.floor(Date.now() / 1000) + 300 });
// 0.8 and later
await session.update({ userId }, { maxAge: "5m" });These configs now throw ERR_SESSION_CONFIG_INVALID:
- A session name ending in a dot and digits, such as
app.1, which is how chunk cookies are spelled. - A
__Host-name with adomain, apathother than/orsecure: false, and a__Secure-name withsecure: false(RFC 6265bis §4.1.3). Browsers drop those cookies.
update() with anything but a plain object or an updater function throws ERR_INVALID_OPTION.
Tokens that are refused, each going to onError rather than throwing:
- A token without
typ: "session+jwt"(RFC 8725 §3.11). - A token without
expwhen the session has amaxAge. A token expires atexpor atiat + maxAge, whichever comes first. - A token whose
iatis later than now plusclockTolerance.
Clearing a session writes Max-Age=0 and an Expires in 1970 (RFC 6265 §5.2.2).
#7. Move hand-written sliding expiry to rolling
Hooks receive the session manager, so a hook can update() or clear() the session it's looking at, and onRead fires once per request. The rolling option replaces a hand-written sliding expiry: it reissues the token once it's that old.
// 0.7: reissue from onRead
hooks: {
async onRead({ event, session, config }) {
if (session.expiresAt - Date.now() < 15 * 60_000) await updateJWSSession(event, config);
},
}
// 0.8 and later
{ key, maxAge: "20m", rolling: "5m" }Hooks covers every hook and its arguments.
#8. Expect stricter tokens on the wire
These checks refuse tokens 0.7 accepted, or change what comes back:
- Padding: base64url must be canonical, so a segment with
=padding is refused (RFC 7515 §2). critandb64: they must sit in the protected header, and every namecritlists must be a parameter that header carries.cty: no longer written into a plain JWT (RFC 7519 §5.2). SetprotectedHeader: { cty: "JWT" }yourself when you nest tokens.- PBES2
p2c: capped at 600 000 on both sides. A higherp2coption isERR_INVALID_OPTION, a token carrying one isERR_JWE_INVALID. - Header tiers:
verifyMultianddecryptMultireturn inprotectedHeaderonly what was protected. ReadalgandencfromsignerHeader,sharedUnprotectedHeaderorrecipientHeaderwhen they sit there (RFC 7515 §7.2.1). - Ed448 and X448: removed.
generateJWK("Ed448")isERR_JWK_UNSUPPORTED. - Limits: every
verifyanddecryptcall is bounded, see Limits. A token or a JWK Set beyond them is refused until you raiselimitson the call. - Guards:
isAsymmetricJWK(value)isfalsefor anything that isn't a JWK, strings included. - JWK Sets: 0.8 skips
octentries in a JWK Set unless you passallowSymmetricJWKSet: true. 0.9 drops that option, and anoctentry is an ordinary candidate there.
#9. Import JOSE plumbing from unjwt/internal
Payload parsing, time-claim computation and crit checks moved from unjwt/utils to unjwt/internal, which has no stability promise:
// 0.7
import { decodePayloadFromBytes } from "unjwt/utils";
const claims = decodePayloadFromBytes(bytes);
// 0.8 and later
import { parsePayloadBytes } from "unjwt/internal";
const claims = parsePayloadBytes<MyClaims>(bytes);0.8 keeps the old names on unjwt/utils as deprecated aliases, and 0.9 removes them; Migrate from 0.8 to 0.9 has the full list.
#10. Fix return types tsc complains about
Skip this section unless tsc reports errors after the upgrade. The payload type follows the options: a literal payload gives the exact type, a variable gives the union.
// A variable typed JWSVerifyOptions yields JWTClaims | string | Uint8Array
const options: JWSVerifyOptions<"json"> = { audience: "https://api.example.com" };
// A claims type argument with payload: "string" is a type error: drop the argument
await verify(token, key, { payload: "string" });
// generateKey<A, { toJWK: true }> becomes generateKey<A, true>
const pair = await generateKey<"ES256", true>("ES256", { toJWK: true });importKey(octJwk) is typed Uint8Array, as it always returned, and WrapKeyResult.epk is EC | OKP, so narrow on kty.