Migrate from 0.8 to 0.9

Update code written for unjwt 0.8.x so it runs on 0.9: sessions through unjwt/session in place of the framework adapters, symmetric JWE session keys, safer cookie defaults, and the removed aliases.

0.9 removes what 0.8 marked as deprecated and tightens a few session defaults. Most of the removals already have their replacement in the latest 0.8.x, so the smoothest path is to upgrade within 0.8 first, clear the deprecation warnings your editor shows, then bump to 0.9. Work through the sections that name something you use; anything not listed behaves as it did.

#Before you start

Four changes reach every app with sessions, so plan for them:

  • Cookie names: the default session cookie becomes a __Host- cookie. Unless you set name, every user signs in again once, and the app needs HTTPS or localhost. See the default cookie names.
  • h3, Nitro and Nuxt: the h3 adapters are gone, and sessions come from unjwt/session. See the first section.
  • JWE session keys: a key pair is refused. See symmetric keys.
  • Config errors at start-up: a session config that can't work throws when the session is defined, not on the first request. See config checks.

On Elysia, the session plugins are gone: see the Elysia adapter.

#Move from the h3 adapters

unjwt/adapters/h3, unjwt/adapters/h3v2 and unjwt/adapters/h3v1 are removed, and with them the per-call functions such as useJWSSession(event, config). An h3 event carries the Web Request as req and the response headers in res, which is exactly what unjwt/session reads, so you pass the event as it is:

// 0.8
import { useJWSSession } from "unjwt/adapters/h3";

app.get("/me", async (event) => (await useJWSSession(event, { key, maxAge: "7D" })).data);

// 0.9: define once at module scope, use on every request
import { defineJWSSession } from "unjwt/session";

const appSession = defineJWSSession({ key, maxAge: "7D" });

app.get("/me", async (event) => (await appSession.use(event)).data);

The JWE functions follow the same pattern with defineJWESession. Each per-call function maps onto the definition:

0.80.9
useJWSSession(event, config), getJWSSession(event, config)defineJWSSession(config).use(event)
getJWSSessionToken(event, config)defineJWSSession(config).token(event)
updateJWSSession(event, config, data)(await definition.use(event)).update(data)
clearJWSSession(event, config)(await definition.use(event)).clear()
signJWSSession(event, config), sealJWESession(event, config)definition.issue(data) for a new token, (await definition.use(event)).token for the current one
verifyJWSSession(event, config, token), unsealJWESession(event, config, token)definition.open(token)

A few things come along with the move:

  • Thrown errors: when the event's res carries errHeaders, as h3's and Nitro's do, every cookie the session writes lands there too, so a handler that throws after update() or clear() still sends the cookie.
  • Event type: use() and every hook's event take a Web session event (a Request, { req, res } or { token }), which an h3 event already is, so no generic is needed. To type the hooks' event as your framework's own, pass it as the third generic: defineJWSSession<Data, MaxAge, H3Event>(config).
  • Error messages: they start with [unjwt/session] instead of [unjwt/h3]. The codes are the same, and your catch should branch on those anyway.

The session state of a request now lives at event.context.unjwt instead of event.context.sessions, which is left to the framework's own session helper. If your code inspected that slot, read the new one.

On Nitro the event is the same, so the edit above is the whole change. On Nuxt 4.6 or later, a handler must come from nuxt/server, whose RequestEvent goes to use() as it is; h3's auto-imported defineEventHandler passes an event without the Web Request, which use() refuses with ERR_SESSION_CONFIG_INVALID:

// 0.9: server/api/me.get.ts
import { defineEventHandler } from "nuxt/server";

export default defineEventHandler(async (event) => (await appSession.use(event)).data);

The recipes show a whole app on h3, Nitro and Nuxt. A framework whose event is none of these gets its own session driver.

#The Elysia adapter is removed

unjwt/adapters/elysia is removed, and with it the jwsSession and jweSession plugins, the requireSession guard, createJWSSession and createJWESession. To keep your sessions, give unjwt/session a session driver for Elysia, as the custom driver recipe does for another framework, and set name: "elysia-jws" or "elysia-jwe", the names 0.8 used, so signed-in users stay signed in. Elysia also has a JWT plugin of its own, @elysiajs/jwt.

#Give encrypted sessions a symmetric key

A JWE session key is symmetric: an oct JWK, a JWK Set of them, or a secret CryptoKey. A key pair, { privateKey, publicKey } or either half alone, throws ERR_SESSION_KEY_INVALID when the session is defined. A pair seals with its public half, so anyone holding that half could mint a session your server accepts.

// 0.8
const appSession = defineJWESession({ key: await generateJWK("RSA-OAEP-256") });

// 0.9: a secret, generated once and kept in the environment
const appSession = defineJWESession({ key: JSON.parse(process.env.SESSION_JWK!) });
// SESSION_JWK = JSON.stringify(await generateJWK("A256GCM"))

To keep a key pair, sign instead: defineJWSSession takes { privateKey, publicKey }. Every session sealed with the old pair is refused once and the user signs in again.

To rotate the key without signing everyone out, pass a JWK Set of the new and the old key as key, the new one first. The first key seals every token, every key in the set opens them, and the token's kid picks the key:

const appSession = defineJWESession({
  key: { keys: [october, september] },
  maxAge: "7D",
});

Once every token sealed with september has expired, drop it from the set. Rotate keys covers the whole pattern.

#Expect a bad session config to stop start-up

defineJWSSession and defineJWESession check the config when you call them. A config that can't work throws while your server starts, where 0.8 threw on the first request that used the session:

ConfigThrows
key missing or a string, a lone private or public JWS key or any JWS key other than an HS* oct JWK, a JWK Set of them, a secret CryptoKey or a key pair, a pair half that is the other half, a pair half without alg that can't serve the algorithm the other half names, a pair whose publicKey can't verify the algorithm it issues withERR_SESSION_KEY_INVALID
A key that names no algorithm (a CryptoKey, an oct JWK without alg, a key pair where neither half names one) and no pinned algorithm, a name like app.1, a __Host- or __Secure- name with attributes its prefix forbidsERR_SESSION_CONFIG_INVALID
A sessionHeader that isn't a header name, rolling without a maxAge or not shorter than itERR_SESSION_CONFIG_INVALID

The JWE key checks of symmetric keys throw at the same point. A key in the right shape that can't be imported, such as a JWK whose k doesn't decode or an AES key of the wrong length, still throws ERR_SESSION_KEY_INVALID from the first use(), issue() or open(). A test that expected one of the errors above from use() now expects it from the definition:

// 0.8
await expect(defineJWESession({ key, rolling: true }).use(request)).rejects.toThrow();

// 0.9
expect(() => defineJWESession({ key, rolling: true })).toThrow();

#Rename the key lookup hook

The two lookup hooks become one name on both kinds of session:

0.80.9
onVerifyKeyLookup (JWS sessions), onUnsealKeyLookup (JWE sessions)onKeyLookup on both, same arguments and result

TypeScript flags the old names. In plain JavaScript an old name is ignored: only key opens tokens, and tokens of your older keys fail to open, so search for both names.

#Take one argument in a key lookup function

A lookup function passed as the key to verify, decrypt and the multi functions receives one object, { header, token }, in place of two arguments. It returns the same keys:

// 0.8
await verify(token, (header) => findKey(header.kid));

// 0.9
await verify(token, ({ header }) => findKey(header.kid));

A lookup that takes no argument, such as () => keys, needs no change. TypeScript flags the old form. In plain JavaScript header is then the object, its kid is undefined, and the lookup finds no key, so search for every lookup you pass.

A lookup or an onKeyLookup that returns undefined for a token it has no key for needs no change: the token is refused with ERR_JWK_KEY_NOT_FOUND, as in 0.8.

#Tell a failed key lookup from a bad token

In 0.8 every failed session read reached onError as ERR_SESSION_TOKEN_INVALID, and an onKeyLookup that threw a JWTError, or returned a key that could not be used, expired the cookie. In 0.9 a cookie is expired only when its token is dead: it fails the session's checks, expires, or onKeyLookup returns undefined for it. Whatever onKeyLookup throws, and a key it returns that cannot be used, is a read failure, ERR_SESSION_READ_FAILED with that error as cause: the session is empty for the request and the cookie is kept. open() throws the same code.

  • onError: branch on error.code. ERR_SESSION_TOKEN_INVALID is a token the visitor can't use again; ERR_SESSION_READ_FAILED is your lookup or its key store, worth an alert.
  • To sign the visitor out anyway: return undefined from onKeyLookup for a token you have no key for, or, in onError, call clear() on the session use(event) returns.
  • token(event): after a failed read it returns the token the request sent, where 0.8 returned undefined. session.token stays undefined then. Two views of the token says which to use.
  • session.error: the session now reports how its read ended, the JWTError its hook received, so a handler can tell a read failure from a dead token without a hook. Tell what happened to the token shows it.

#List the algorithms a session reads

In 0.8 a pinned session read tokens of the pinned algorithm alone, and an unpinned one what its key, or the keys its lookup hook returned, named. In 0.9 the pin, jws.signOptions.alg or jwe.encryptOptions.alg, decides only what tokens are issued with. A session reads the algorithms its configured key serves, and jws.verifyOptions.algorithms or jwe.decryptOptions.algorithms, an option sessions take from 0.9, adds more:

  • A key that names no algorithm: a CryptoKey, or an oct JWK without alg, needs the pin, or defining the session throws ERR_SESSION_CONFIG_INVALID. In a key pair, a half that names none takes the algorithm the other half names, so only a pair where neither half names one needs the pin.
  • An EC or Ed25519 JWK without alg: sign and signMulti take the algorithm from its curve, ES256, ES384, ES512 or EdDSA, where 0.8 threw ERR_JWS_ALG_MISSING or ERR_JWS_SIGNER_ALG_INFERENCE, and a session key pair of such JWKs issues with it and needs no pin.
  • A publicKey list: a pinned session reads the alg of every public key in the list, not the pin alone. Take a key out of the list to refuse its tokens. A key in the list without alg, other than an EC or Ed25519 key, reads the private key's algorithm when its material carries it, and any other only from jws.verifyOptions.algorithms; one that serves neither makes defining the session throw ERR_SESSION_CONFIG_INVALID.
  • Keys from onKeyLookup: a token is read only under an algorithm the configured key serves or algorithms lists, whatever keys the hook returns. List the algorithm of older keys that differ:
// 0.9: an HS512 key issues, older HS256 keys still open their tokens
defineJWSSession({
  key: hs512,
  jws: { verifyOptions: { algorithms: ["HS256"] } },
  hooks: { onKeyLookup: () => ({ keys: [hs512, ...olderHs256] }) },
});

Or pass the keys as a JWK Set key, { keys: [hs512, ...olderHs256] }, and drop the hook: each key in the set serves its own alg, so the session reads HS256 tokens with no list.

An empty list, or one naming an algorithm no configured key serves while onKeyLookup is unset, throws ERR_SESSION_CONFIG_INVALID when the session is defined.

#Name the session header

sessionHeader is opt-in. Left unset or false, a session reads cookies only; 0.8 also read x-<name>-session when it was unset. Set sessionHeader: true for x-<name>-session, or pass a header name of your own:

// 0.8: reads x-unjwt-jws-session, else the cookie
defineJWSSession({ key });

// 0.9: the same behaviour
defineJWSSession({ key, sessionHeader: true });

0.8.5 read the header first whenever a request sent it, and such a request never wrote a cookie back, whatever the cookie held. 0.9 compares the two:

The request sends0.8.50.9
the header aloneread from the header, no cookie writtenthe same
the header and the same token in the cookieread from the header, no cookie writtena cookie session: update() and rolling write the cookie, a bad token's cookie is expired
the header and another cookieread from the header, no cookie writtenread from the header, no cookie written, the cookie left as it is

A page that mirrors its cookie into the header gets its cookie writes back, and update() on such a request without a response throws ERR_SESSION_READONLY_EVENT, as on any cookie session. As before, a header token that fails to open gives an empty session and never falls back to the cookie. session.source, "cookie", "header" or "token", tells you which one a request ran on; it is on the session, on what every hook receives and on what open() returns. Sessions without cookies shows the flows.

A header-only session, cookie: false, also needs sessionHeader now. Without it, use(event) throws ERR_SESSION_CONFIG_INVALID (Session has no token source). issue(), open() and use({ token }) still work on such a config, because they never read a request.

#Rolling stops on header and handed tokens

rolling reissues a session read from its cookie, and nothing else. 0.8.5 also reissued a token read from the session header or passed as use({ token }), onto session.token, where nothing sent it unless your handler did. In 0.9 such a session keeps the token the client sent, and onUpdate with trigger: "rolling" no longer fires for it. A client that needs a fresh token asks for one, and the handler calls update() and returns session.token:

// 0.9: a refresh endpoint for clients that send the token themselves
const session = await apiSession.use({ req });
await session.update();
return Response.json({ token: session.token });

The default names carry the __Host- prefix, which tells the browser the cookie is Secure, sent from the whole site and never shared with subdomains:

Entry0.8 default0.9 default
unjwt/session, signedunjwt-jws__Host-unjwt-jws
unjwt/session, encryptedunjwt-jwe__Host-unjwt-jwe
h3 adapters, signed and encryptedh3-jws, h3-jwe__Host-unjwt-jws, __Host-unjwt-jwe

The library sets Secure, Path=/ and no Domain for you; what you need is HTTPS, or localhost while you develop. A browser drops a __Host- cookie on a plain HTTP host. The session header name doesn't change: x-unjwt-jws-session drops the prefix.

Cookies issued under the old name are ignored, so users sign in again once. To keep them signed in, set the old name:

defineJWSSession({ key, name: "unjwt-jws" });

#Mark signed session cookies readable, if you read them

A signed session's cookie defaults to HttpOnly, like an encrypted one, so page scripts can't read it. That's the right default when nothing in the page reads the session. If your front end decodes the cookie, opt out:

defineJWSSession({ key, cookie: { httpOnly: false } });

#Drop allowSymmetricJWKSet

The option is gone, and an oct key in a JWK Set is an ordinary candidate, like any other entry. Remove the option from verify, decrypt, the multi functions and the session configs. An option left in place is ignored.

A set you fetch from somewhere else should hold only public keys. Pin algorithms to the asymmetric ones you expect, such as algorithms: ["ES256"], and an HS256 token is refused before any key is tried, whatever the set holds. Use a JWK Set covers filtering.

#Replace the removed aliases

The names 0.8 marked as deprecated are gone. Each one has a direct replacement:

0.80.9
forceUint8Array: true (verify, decrypt and the multi functions)payload: "bytes"
exportKey(key) (unjwt/jwk)exportJWK(key), same arguments and result
base64UrlEncode, base64UrlDecode (unjwt/utils)base64UrlStringify, base64UrlParse
base64Encode, base64Decode (unjwt/utils)base64Stringify, base64Parse
DecodeOptions (unjwt/utils)Base64ParseOptions
BytesSource (unjwt/utils)string | Uint8Array, what the codecs take
applyTypCtyDefaults (unjwt/utils)applyTypDefault (unjwt/internal)
decodePayloadFromBytes, decodePayloadFromB64UrlSegment (unjwt/utils)parsePayloadBytes, parsePayloadSegment (unjwt/internal)
getPlaintextBytes, computeJwtTimeClaims (unjwt/utils)the same names on unjwt/internal
validateCriticalHeadersJWS, validateCriticalHeadersJWE, assertCritShape (unjwt/utils)the same names on unjwt/internal
DecodePayloadOptions, ComputeJwtTimeClaimsOptions (unjwt/utils)ParsePayloadOptions, ComputeJwtTimeClaimsOptions (unjwt/internal)
SessionConfigJWS, SessionConfigJWE and the other session types (unjwt/adapters/h3*)the same names on unjwt/session

TypeScript flags a leftover forceUint8Array. In plain JavaScript it's ignored, and the payload comes back as a claims object instead of bytes, so search for it. unjwt/internal has no stability promise; Utilities says what that means.

#Expect one key-attempt budget per multi call

verifyMulti, verifyMultiAll and decryptMulti share one budget of key trials across every signature or recipient, set by limits.keyAttempts and 16 by default. One key tried on each of 16 entries fits; a JWK Set of 8 keys tried on each of three entries without a kid does not. The trial past the budget throws ERR_JWK_KEY_NOT_FOUND and ends the call:

await verifyMultiAll(jws, jwks, { limits: { keyAttempts: 32 } });

Raise it only for a token you expect to need it. Signing with a kid, so each entry names its key, keeps the trials at one per entry. Limits lists every bound.

#Read each entry's failure from a multi call

When no entry of a token with two or more signatures or recipients opens, verifyMulti and decryptMulti throw one code, ERR_JWS_SIGNATURE_INVALID or ERR_JWE_DECRYPTION_FAILED, with one JWTError per signature or recipient, in order, as cause. 0.8 threw the error of the last entry it tried, so the code depended on how the token was built. A token with a single signature or recipient throws that entry's own error, the same code verify or decrypt gives for the same failure:

// 0.8: whatever the last signature failed with, such as ERR_JWS_ALG_NOT_ALLOWED
// 0.9, for a token with two or more signatures
const error = await verifyMulti(jws, keys).catch((e) => e);
error.code; // "ERR_JWS_SIGNATURE_INVALID"
error.cause.map((entry) => entry.code); // one code per signature

The failures that are an entry's own land in cause too: more JWK Set candidates than limits.keyCandidates (ERR_JWK_KEY_NOT_FOUND), the recipient that would pass limits.pbes2Iterations (ERR_JWE_INVALID), and an entry strictSignerMatch or strictRecipientMatch skipped (ERR_JWS_NO_MATCHING_SIGNER, ERR_JWE_NO_MATCHING_RECIPIENT); on a token with a single entry, that failure is the error thrown. A failure of the whole token, a strict match that tried no entry, and a spent limits.keyAttempts throw as before.

#Drop claim options a call can't check

0.8 ignored a claim option the call never checked. 0.9 throws ERR_INVALID_OPTION instead, so an issuer you set is never silently skipped:

CallOptions that throw
verify, decrypt and the multi variants with payload: "string" or "bytes", or with validateClaims: falseaudience, issuer, subject, maxTokenAge, requiredClaims
sign, encrypt and the multi variants with a string or bytes payloadexpiresIn, expiresAt, notBeforeIn, notBeforeAt, issuedAt

clockTolerance and currentDate are still accepted in every mode. Drop the options, or read the payload as JSON so they're checked:

// 0.8: issuer was never checked
await verify(token, key, { payload: "string", issuer: "https://auth.example.com" });

// 0.9
await verify(token, key, { payload: "string" });

#Expect ERR_JWK_INVALID for a missing or mismatched key

  • No key: verify and decrypt with an undefined or null key throw ERR_JWK_INVALID ("A key is required."), where 0.8 threw an algorithm error.
  • A key type that can't serve the algorithm: importKey refuses an alg the key's type can't serve, such as an oct JWK imported for ES256 or an EC JWK for HS256, with ERR_JWK_INVALID.
  • Key agreement on two curves: deriveSharedSecret wraps a failed agreement, such as a P-256 key against an X25519 one, in ERR_JWK_INVALID. Its types take X25519 JWKs as well as EC ones.

#Name dir for an AES CryptoKey

When you decrypt with an AES-KW or AES-GCM CryptoKey, the library infers only its key-wrapping algorithm, A256KW or A256GCMKW for a 256-bit key. Using the key directly as the content key needs dir spelled out:

// 0.8: dir was inferred
await decrypt(token, aesKey);

// 0.9
await decrypt(token, aesKey, { algorithms: ["dir"] });

Without it, a dir token throws ERR_JWE_ALG_NOT_ALLOWED. An oct JWK whose alg names a content algorithm, such as A256GCM, still means dir.