Configure a session
Define a session once with its key, lifetime, cookie and token sources, and type the data it carries.
You define a session once, when your server starts, and use that one definition in every request. The definition holds everything that stays the same between requests: the key, how long a session lives, what the cookie is called and whether a request header may carry the token instead. Sessions explains how a session runs; this page is about the settings.
#Before you start
- A key that survives restarts. A key generated at start-up signs everyone out on every deploy, so make one once and keep it with your other secrets.
- HTTPS in production. The default cookie names start with
__Host-, which browsers accept only over a secure connection; most also treathttp://localhostas one. - Session data travels in the cookie. Keep it small: user ID, role, a few flags. A cookie holds about 4 KB, and a session splits across at most 16 of them.
#Make a session key
Run this once and store the printed JSON in an environment variable, SESSION_KEY on this page:
import { generateJWK } from "unjwt/jwk";
console.log(JSON.stringify(await generateJWK("A256GCM")));
// {"alg":"A256GCM","kty":"oct","k":"…","kid":"…"}A256GCM gives an oct key, one secret that both seals and opens, for an encrypted session. The JWK names its algorithm in alg and carries a kid: keep both, on every key you make later too, so the session reads each key's algorithm from the key and a token's kid picks its key when you rotate to a new one. For a signed session, generateJWK("HS256") gives the same kind of key for signing, and generateJWK("ES256") a key pair. Generate keys lists the other algorithms.
#Define an encrypted session
defineJWESession from unjwt/session returns the definition you import wherever a handler needs the session:
import { type JWK_oct, defineJWESession } from "unjwt/session";
// An "oct" JWK as JSON: generateJWK("A256GCM"), made once and kept with your secrets
const json = process.env.SESSION_KEY;
if (!json) throw new Error("SESSION_KEY is not set");
const key: JWK_oct<"A256GCM"> = JSON.parse(json);
export interface AppSession {
userId: string;
role: "member" | "admin";
workspaceId?: string;
}
export const appSession = defineJWESession<AppSession, "7D">({
key,
maxAge: "7D",
rolling: "1D",
});- Fail at start-up: without
SESSION_KEYthe module throws before the server takes a request, and so does a key of the wrong kind, such as a key pair half:defineJWESessionthrowsERR_SESSION_KEY_INVALID. Anoctkey whose secret doesn't import, such as one of the wrong length, throwsERR_SESSION_KEY_INVALIDfrom the firstuse(). - Types:
AppSessiontypessession.data, and"7D"makesexpiresAtanumber. TypeScript infers every type argument or none, so the lifetime is named again next to the data. A module that exports the definition to other files can annotate it instead,export const appSession: SessionDefinition<AppSession, "7D"> = defineJWESession({ … }), for the same type. maxAge: each token expires seven days after it was issued, and so does its cookie.rolling: a token that is at least a day old is replaced on the next request, so an active visitor stays signed in. Set the lifetime has the details.- A copy of the config: the session copies the object you pass when it is defined, so changing that object later has no effect. For other settings, define another session.
#Define a signed session
A JWS session signs its data instead of encrypting it. Pick one when the data is not secret and you want other services to verify the token with only a public key:
import { type JWK_EC_Private, defineJWSSession, toPublicJWK } from "unjwt/session";
// A private ES256 JWK as JSON; services that only verify get its public half
const json = process.env.SESSION_SIGNING_KEY;
if (!json) throw new Error("SESSION_SIGNING_KEY is not set");
const privateKey: JWK_EC_Private<"ES256"> = JSON.parse(json);
export interface SignedSession {
userId: string;
locale: string;
}
export const signedSession = defineJWSSession<SignedSession, "1h">({
key: { privateKey, publicKey: toPublicJWK(privateKey) },
maxAge: "1h",
jws: { signOptions: { alg: "ES256" } },
});- Key pair: the private half signs, the public half verifies.
toPublicJWKderives the public half, so one variable is enough. - Pinned algorithm:
jws.signOptions.algsigns every token with ES256. The session accepts the algorithms its key serves, ES256 alone for this key, and a pin the key can't serve stops start-up withERR_SESSION_KEY_INVALID. - Readable data: anyone holding the token can decode the data. The cookie is
HttpOnly, so page scripts cannot read it;cookie: { httpOnly: false }lets them, and also lets an injected script copy the token.
#Load the key from PEM
A key store or a secret manager often hands out the private key as PEM text. importPEM turns it into a private JWK, and toPublicJWK derives the public half. A JWS session with a key pair needs both halves: the private one signs, the public one verifies.
import { defineJWSSession, importPEM, toPublicJWK } from "unjwt/session";
// A PKCS#8 private key, "-----BEGIN PRIVATE KEY-----…", as your key store hands it out
const pem = process.env.SESSION_SIGNING_PEM;
if (!pem) throw new Error("SESSION_SIGNING_PEM is not set");
const privateKey = await importPEM(pem, "ES256", {
pemType: "pkcs8",
jwkParams: { kid: "2026-10" },
});
export const signedSession = defineJWSSession<{ userId: string }, "1h">({
key: { privateKey, publicKey: toPublicJWK(privateKey) },
maxAge: "1h",
});pemType: "pkcs8": the PEM holds a private key. A public key's PEM failsimportPEMwithERR_JWK_INVALID, before the session is defined.kid:jwkParamsnames the key, and every token carries thatkidin its header, so you can rotate to a new key later.
#Choose a key
| Session | key takes |
|---|---|
| JWS | An HS256/384/512 oct JWK, a secret CryptoKey, or { privateKey, publicKey } where privateKey is a private JWK or CryptoKey and publicKey a public CryptoKey, one public JWK, a list of them or a JWK Set. |
| JWS, several keys | A JWK Set of HS256/384/512 oct JWKs, JWKSet<JWK_oct<JWK_HMAC>[]>. |
| JWE | An oct JWK or a secret CryptoKey. |
| JWE, several keys | A JWK Set of oct JWKs, JWKSet<JWESessionOctJWK[]>. |
- No lone asymmetric JWS key: a private or public key alone, JWK or
CryptoKey, can't both sign and verify.defineJWSSessionrefuses one withERR_SESSION_KEY_INVALID; pass both halves as{ privateKey, publicKey }. - No asymmetric JWE key: a key pair would seal with its public half, and anyone holding that half could mint a session your server accepts.
defineJWESessionrefuses one withERR_SESSION_KEY_INVALID; usedefineJWSSessionfor a key pair. - No password: a string throws
ERR_SESSION_KEY_INVALID. Turn a password into a key once withderiveJWKFromPassword. - A key that names no algorithm: a
CryptoKey, or anoctJWK withoutalg, needs the algorithm it issues with pinned:jws.signOptions.alg, orjwe.encryptOptions.algandenc. Without the pin, defining the session throwsERR_SESSION_CONFIG_INVALID. A key pair of EC or Ed25519 JWKs withoutalgneeds no pin: the curve names the algorithm,ES256for P-256 orEdDSAfor Ed25519, and the session issues with it. - A key pair with one half that names its algorithm: the other half takes that algorithm. A private JWK with
alg: "ES256"beside a publicCryptoKey, or a privateCryptoKeybeside one public JWK withalg, issues every token with it and needs no pin; only a pair where neither half names one needsjws.signOptions.alg. A half that can't serve the other's algorithm, such as an RSA publicCryptoKeybeside an ES256 private JWK, makes defining the session throwERR_SESSION_KEY_INVALID. In apublicKeylist or JWK Set, a JWK that names no algorithm, such as an RSA JWK withoutalg, takes the private half's. - A public half that verifies what the pair issues: a single public JWK that names an algorithm names the one the session issues with, the pin or else the private half's, and a
publicKeylist or JWK Set holds at least one key that serves it. Keys of other algorithms may sit beside it and verify their own tokens. An ES384 public JWK beside an ES256 private one, or a list of RS256 and PS256 keys, makes defining the session throwERR_SESSION_KEY_INVALID:The session key "publicKey" names "ES384", not the "ES256" that the session key "privateKey" names. - A pin and a key that names its algorithm: they must agree,
HS256withjws.signOptions.alg: "HS256", or anA256GCMkey withjwe.encryptOptions.alg: "dir". A pin the key cannot serve makes defining the session throwERR_SESSION_KEY_INVALID. - A JWK Set: its first key issues every token, and every key in it opens them. Each key is checked as a lone key would be, so an empty set, or an entry that isn't an
octJWK, aCryptoKeyincluded, throwsERR_SESSION_KEY_INVALID, and a pin must agree with the first key. Rotate keys puts the newest key first; a key pair takes the earlier public halves in itspublicKeylist. - Types:
unjwt/sessionexports the two shapes asJWSSessionKeyandJWESessionKey, andJWESessionOctJWKfor theoctJWK an encrypted session takes, to type a key variable.
#The algorithms a session accepts
The pin decides what each token is issued with. When it reads a token, a session accepts every algorithm its keys serve:
- A JWK with
alg: that algorithm. An EC or OKP JWK withoutalgserves the one its curve names. - A key that names none: those its material can carry among the pin, or in a key pair the algorithm the other half names, and the algorithms
algorithmslists. - A JWK Set or a key pair: what each key in the set, or each public key in
publicKey, serves, so they may mix algorithms. - An encrypted session's
enc: a key-wrapping key opens tokens of every content encryption, adirkey only its own.
jws.verifyOptions.algorithms or jwe.decryptOptions.algorithms adds algorithms to that list. Leave it unset unless a key needs it:
- A key without
algin a JWK Set or apublicKeylist, such as an RSA key that verifiesPS256under anES256pin, or an older HMAC key behind the first. Without it, defining the session throwsERR_SESSION_CONFIG_INVALID. - Keys of another algorithm that only
onKeyLookupreturns, and the algorithms aCryptoKeyit returns serves, as in Rotate with onKeyLookup.
A JWK Set whose keys all carry alg needs no list, whatever algorithms they mix, as in Change the algorithm. An empty list throws ERR_SESSION_CONFIG_INVALID when the session is defined, and so does an algorithm no configured key serves, unless onKeyLookup is set, since the keys it returns may serve it.
#Set the lifetime
maxAge takes seconds or a duration such as "15m", "12h" or "7D". Each token gets exp set to its issue time plus maxAge, and the cookie expires with it. When a request comes in, the session also ends at its issue time plus your current maxAge, even if the token's own exp is later. Shortening maxAge therefore shortens every session already out there. Without maxAge, tokens never expire and cookies last until the browser closes.
rolling replaces a cookie session's token as it is read, so the expiry moves forward while the visitor is active. It needs a maxAge:
rolling | With maxAge: "1h" |
|---|---|
| unset | Each token ends one hour after it was issued, however often it is read. |
true | Every request issues a fresh one-hour token. |
"15m" | Requests in the first 15 minutes of a token change nothing; the first one after that issues a fresh hour. |
- A duration must be shorter than
maxAge, or defining the session throwsERR_SESSION_CONFIG_INVALID. - Neither form caps the total life of a session: one request per hour keeps it going. To sign people out after 30 days whatever they do, keep the sign-in time in the data and check it, as Hooks does.
- Only a session read from its cookie rolls. A session read from the header or from a token in hand keeps the token the client sent; refresh it with
update()and send the new one back. - A request that cannot write a cookie, such as one passed to
use()without a response, does not roll. The next request carries the same token and rolls it. - A roll keeps the data as it is. To compute part of it again, such as a user's grants, update it in
onReadwhenroll.dueistrue, as Hooks does, or leave the roll to the next request when the data cannot be fetched.
#Name the cookie
The default names are __Host-unjwt-jws and __Host-unjwt-jwe. A __Host- cookie can only be set by your exact host, over HTTPS, for the whole site. No sibling subdomain can plant one with the same name to replace your session. The browser enforces this when the cookie is Secure, has Path=/ and no Domain, which is what the session sets.
name sets another name, and defining the session checks it against the prefix it uses. A __Host- name without secure, with a domain or with a path other than / throws ERR_SESSION_CONFIG_INVALID, and so does a __Secure- name without secure. A name ending in a dot and digits, such as app.1, is refused too, because it spells a part of a split cookie.
On a development host reached over plain HTTP, such as your laptop's address on the local network, pick a plain name and drop Secure:
const appSession = defineJWESession({
key,
name: "app-session",
cookie: { secure: false },
});Keep the __Host- name in production: read the two settings from your environment rather than shipping this.
#Change cookie attributes
cookie takes the attributes of the session cookie. Both kinds of session start from the same defaults:
| Attribute | Default | Notes |
|---|---|---|
path | "/" | A __Host- name requires it. |
secure | true | A __Host- or __Secure- name requires it. |
httpOnly | true | false lets page scripts read the cookie. |
sameSite | "lax" | "strict", "none" (needs secure) or true for strict. |
expires | the token's expiry | Set from the token when it expires; your own value only for a token without an expiry. |
maxAge | none | Ignored for a token that expires, so the cookie and the token expire together. |
domain | none | Not allowed with a __Host- name. |
priority | none | "low", "medium" or "high". |
partitioned | none | For a cookie in a third-party context (CHIPS). |
chunkMaxLength | 4000 | Characters per cookie before the token is split. |
A token longer than chunkMaxLength is split: the cookie under the session's name holds __chunked__N, and the parts follow as <name>.1 to <name>.N. A session reads them back together, and expires the leftover parts of a longer earlier token. A token that needs more than 16 parts fails the update() with ERR_SESSION_INVALID and the session keeps its previous state. A roll reissues the token inside use(), so there use() rejects.
#Accept the token in a header
Apps and scripts that keep the token themselves send it in a request header instead of a cookie. sessionHeader names that header:
const apiSession = defineJWSSession({
key,
sessionHeader: "x-acme-session",
});- Values: the header holds the token alone or
Bearer <token>. Any other value, such asBasic …, still counts as a header sent: the session is empty andonErrorhears about it. true: readsx-<name>-session, the name without its__Host-or__Secure-prefix, sox-unjwt-jws-sessionfor the default JWS name.- Unset or
false: no header is read at all, cookies only.
Each request picks its token source once, before the token is opened, and keeps it for the whole request. session.source reports it:
| The request sends | session.source | update() reaches | clear() |
|---|---|---|---|
| the cookie alone | "cookie" | the cookie | expires the cookie |
| the header and the same token in the cookie | "cookie" | the cookie | expires the cookie |
| the header alone | "header" | session.token alone | empties the session for this request |
| the header and another cookie | "header" | session.token alone; the cookie stays as it is | empties the session; the cookie stays as it is |
a token passed as use({ token }) | "token" | session.token alone | empties the session for this request |
- Same token, cookie session: a page that mirrors its cookie into the header keeps every cookie behaviour:
update()writes the cookie,rollingreissues it, and a bad token's cookie is expired. The two are compared as text, a split cookie joined first. - Another token, header session: the cookie is neither read nor written. A header token that is expired or tampered with gives an empty session, and the cookie is not tried instead.
- Nothing written for a header:
update()puts the new token onsession.token, and sending it back is your job. Sessions without cookies shows the whole flow.
With sessionHeader set, cookie: false turns the cookie off: every request is read from the header, and a request without it gets an empty session. A session with neither a cookie nor a header has nowhere to read a token from a request: use() and token() on a request throw ERR_SESSION_CONFIG_INVALID, while use({ token }), issue() and open() still work. That is the shape for tokens you send by other means, such as a magic link.
#Pass options to signing and encryption
jws and jwe hand options through to the functions that make and check the token:
| Option | Session | Takes |
|---|---|---|
jws.signOptions | JWS | sign options, without expiresIn, expiresAt, notBeforeIn and notBeforeAt. alg is the algorithm every token is signed with. |
jws.verifyOptions | JWS | verify options such as issuer, audience, clockTolerance, limits and algorithms, without typ, maxTokenAge and payload. |
jwe.encryptOptions | JWE | encrypt options, without the four time options. alg and enc are the algorithms every token is encrypted with. |
jwe.decryptOptions | JWE | decrypt options such as clockTolerance, minIterations, maxIterations and algorithms, without encryptionAlgorithms, typ, maxTokenAge and payload. |
Every session token carries the type session+jwt in its protected header, and a session opens only tokens of that type, so a token your app issues for some other purpose is never taken for a session. protectedHeader.typ in signOptions or encryptOptions sets another type. algorithms adds to the algorithms a session accepts, as The algorithms a session accepts describes.
#When it fails
defineJWSSession and defineJWESession check every setting the config decides on its own, so a wrong one stops your server at start-up instead of failing a request. The rest throws from the first call that meets it:
| Situation | What happens |
|---|---|
key missing, a string, a key of the wrong kind or half, a lone private or public key, or an asymmetric key on a JWE session | Defining the session throws ERR_SESSION_KEY_INVALID. |
An empty JWK Set, or a set entry that isn't an oct JWK of the session's kind, such as a CryptoKey | Defining the session throws ERR_SESSION_KEY_INVALID. |
A JWK Set key without kid whose tokens would meet more keys than limits.keyCandidates: those of their algorithm and those without alg | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
A CryptoKey or an oct JWK without alg, or a key pair neither half of which names an algorithm, and no pinned algorithm | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
A key without alg in a JWK Set or a publicKey list, whose algorithm neither the pin, the private key's alg nor algorithms names | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
algorithms empty, or naming an algorithm no key serves while onKeyLookup is unset | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
A pin the key can't serve, such as an HS256 JWK with signOptions.alg: "HS512" or a 256-bit AES CryptoKey with encryptOptions.alg: "A128KW" | Defining the session throws ERR_SESSION_KEY_INVALID. |
A key pair half without alg that can't serve the algorithm the other half names, such as an RSA public CryptoKey beside an ES256 private JWK | Defining the session throws ERR_SESSION_KEY_INVALID. |
A key pair whose public JWK names another algorithm than the one it issues with, or whose publicKey list or JWK Set holds no key that serves it | Defining the session throws ERR_SESSION_KEY_INVALID. |
__Host- or __Secure- name with attributes the prefix forbids, or a name like app.1 | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
rolling without maxAge, or not shorter than it | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
sessionHeader that is not a header name | Defining the session throws ERR_SESSION_CONFIG_INVALID. |
A JWK of the right kind that doesn't import, such as a k that doesn't decode or an AES key of the wrong length | The first use(), issue() or open() throws ERR_SESSION_KEY_INVALID. |
cookie: false and no sessionHeader | use() and token() on a request throw ERR_SESSION_CONFIG_INVALID. |
| A token that needs more than 16 cookies | update() throws ERR_SESSION_INVALID, or use() when a roll issues the token. |
Handle errors lists every code.
#Options
| Option | Default | Notes |
|---|---|---|
key | required | See Choose a key. |
maxAge | none: tokens never expire | Seconds or a duration. Also bounds tokens as they are read. |
rolling | none | true or a duration shorter than maxAge. Cookie sessions only. |
name | "__Host-unjwt-jws" / "__Host-unjwt-jwe" | Cookie name, and the base of the sessionHeader: true header name. |
cookie | see the table | Attributes, or false for no cookie. |
sessionHeader | none: cookies only | A header name, or true for x-<name>-session. See the header. |
generateId | crypto.randomUUID | Makes each token's ID, the jti claim. |
jws / jwe | none | See Pass options. |
hooks | none | See Hooks. |
#Going further
- Use the session: Read, update and clear.
- React to what happens: Hooks covers revocation, audit logs and key rotation.
- Another framework: Write a driver runs the same config on a framework that exposes cookies its own way.