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 treat http://localhost as 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:

app-session.ts
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_KEY the module throws before the server takes a request, and so does a key of the wrong kind, such as a key pair half: defineJWESession throws ERR_SESSION_KEY_INVALID. An oct key whose secret doesn't import, such as one of the wrong length, throws ERR_SESSION_KEY_INVALID from the first use().
  • Types: AppSession types session.data, and "7D" makes expiresAt a number. 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:

signed-session.ts
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. toPublicJWK derives the public half, so one variable is enough.
  • Pinned algorithm: jws.signOptions.alg signs 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 with ERR_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.

pem-signing-key.ts
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 fails importPEM with ERR_JWK_INVALID, before the session is defined.
  • kid: jwkParams names the key, and every token carries that kid in its header, so you can rotate to a new key later.

#Choose a key

Sessionkey takes
JWSAn 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 keysA JWK Set of HS256/384/512 oct JWKs, JWKSet<JWK_oct<JWK_HMAC>[]>.
JWEAn oct JWK or a secret CryptoKey.
JWE, several keysA 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. defineJWSSession refuses one with ERR_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. defineJWESession refuses one with ERR_SESSION_KEY_INVALID; use defineJWSSession for a key pair.
  • No password: a string throws ERR_SESSION_KEY_INVALID. Turn a password into a key once with deriveJWKFromPassword.
  • A key that names no algorithm: a CryptoKey, or an oct JWK without alg, needs the algorithm it issues with pinned: jws.signOptions.alg, or jwe.encryptOptions.alg and enc. Without the pin, defining the session throws ERR_SESSION_CONFIG_INVALID. A key pair of EC or Ed25519 JWKs without alg needs no pin: the curve names the algorithm, ES256 for P-256 or EdDSA for 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 public CryptoKey, or a private CryptoKey beside one public JWK with alg, issues every token with it and needs no pin; only a pair where neither half names one needs jws.signOptions.alg. A half that can't serve the other's algorithm, such as an RSA public CryptoKey beside an ES256 private JWK, makes defining the session throw ERR_SESSION_KEY_INVALID. In a publicKey list or JWK Set, a JWK that names no algorithm, such as an RSA JWK without alg, 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 publicKey list 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 throw ERR_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, HS256 with jws.signOptions.alg: "HS256", or an A256GCM key with jwe.encryptOptions.alg: "dir". A pin the key cannot serve makes defining the session throw ERR_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 oct JWK, a CryptoKey included, throws ERR_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 its publicKey list.
  • Types: unjwt/session exports the two shapes as JWSSessionKey and JWESessionKey, and JWESessionOctJWK for the oct JWK 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 without alg serves 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 algorithms lists.
  • 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, a dir key 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 alg in a JWK Set or a publicKey list, such as an RSA key that verifies PS256 under an ES256 pin, or an older HMAC key behind the first. Without it, defining the session throws ERR_SESSION_CONFIG_INVALID.
  • Keys of another algorithm that only onKeyLookup returns, and the algorithms a CryptoKey it 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:

rollingWith maxAge: "1h"
unsetEach token ends one hour after it was issued, however often it is read.
trueEvery 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 throws ERR_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 onRead when roll.due is true, as Hooks does, or leave the roll to the next request when the data cannot be fetched.

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.

cookie takes the attributes of the session cookie. Both kinds of session start from the same defaults:

AttributeDefaultNotes
path"/"A __Host- name requires it.
securetrueA __Host- or __Secure- name requires it.
httpOnlytruefalse lets page scripts read the cookie.
sameSite"lax""strict", "none" (needs secure) or true for strict.
expiresthe token's expirySet from the token when it expires; your own value only for a token without an expiry.
maxAgenoneIgnored for a token that expires, so the cookie and the token expire together.
domainnoneNot allowed with a __Host- name.
prioritynone"low", "medium" or "high".
partitionednoneFor a cookie in a third-party context (CHIPS).
chunkMaxLength4000Characters 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 as Basic …, still counts as a header sent: the session is empty and onError hears about it.
  • true: reads x-<name>-session, the name without its __Host- or __Secure- prefix, so x-unjwt-jws-session for 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 sendssession.sourceupdate() reachesclear()
the cookie alone"cookie"the cookieexpires the cookie
the header and the same token in the cookie"cookie"the cookieexpires the cookie
the header alone"header"session.token aloneempties the session for this request
the header and another cookie"header"session.token alone; the cookie stays as it isempties the session; the cookie stays as it is
a token passed as use({ token })"token"session.token aloneempties 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, rolling reissues 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 on session.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:

OptionSessionTakes
jws.signOptionsJWSsign options, without expiresIn, expiresAt, notBeforeIn and notBeforeAt. alg is the algorithm every token is signed with.
jws.verifyOptionsJWSverify options such as issuer, audience, clockTolerance, limits and algorithms, without typ, maxTokenAge and payload.
jwe.encryptOptionsJWEencrypt options, without the four time options. alg and enc are the algorithms every token is encrypted with.
jwe.decryptOptionsJWEdecrypt 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:

SituationWhat 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 sessionDefining 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 CryptoKeyDefining 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 algDefining 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 algorithmDefining 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 namesDefining the session throws ERR_SESSION_CONFIG_INVALID.
algorithms empty, or naming an algorithm no key serves while onKeyLookup is unsetDefining 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 JWKDefining 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 itDefining the session throws ERR_SESSION_KEY_INVALID.
__Host- or __Secure- name with attributes the prefix forbids, or a name like app.1Defining the session throws ERR_SESSION_CONFIG_INVALID.
rolling without maxAge, or not shorter than itDefining the session throws ERR_SESSION_CONFIG_INVALID.
sessionHeader that is not a header nameDefining 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 lengthThe first use(), issue() or open() throws ERR_SESSION_KEY_INVALID.
cookie: false and no sessionHeaderuse() and token() on a request throw ERR_SESSION_CONFIG_INVALID.
A token that needs more than 16 cookiesupdate() throws ERR_SESSION_INVALID, or use() when a roll issues the token.

Handle errors lists every code.

#Options

OptionDefaultNotes
keyrequiredSee Choose a key.
maxAgenone: tokens never expireSeconds or a duration. Also bounds tokens as they are read.
rollingnonetrue 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.
cookiesee the tableAttributes, or false for no cookie.
sessionHeadernone: cookies onlyA header name, or true for x-<name>-session. See the header.
generateIdcrypto.randomUUIDMakes each token's ID, the jti claim.
jws / jwenoneSee Pass options.
hooksnoneSee 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.