This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

Server-SideUser Sessions

User Sessions

Carry the user's session, and the request's own headers, to your API — from a page the server renders, through the proxy, and from the browser.

15 min readUpdated both modes

The problem it solves

A server that renders a page for a user calls the API on that user's behalf, and its own fetch carries none of the user's cookies. Handing the call the incoming headers whole sends too much: every cookie of your application — its own session, analytics, preferences — and the headers the browser addressed to your application rather than to the API, whatever host the API is on.

An API that keeps a session says so where it is defined. Courier then sends each call made for a user the cookies that hold the session and nothing else, repeats the double-submit token a write needs, refuses a write another site set off, and carries the cookies the API sets back to the user's browser. Security Model shows where these credentials travel through every layer, and what Courier refuses and keeps out of its logs.

Describe the session

api/index.ts
import { courier, defineApi } from "@noverax/courier/define"

const { endpoint } = courier()

export const api = defineApi({
  name: "api",
  baseURL: process.env.API_URL!,
  // The cookies the API keeps the user's session in, and the token it asks writes to repeat
  session: {
    cookies: ["sessionid", "logto_*"],
    csrf: { cookie: "csrftoken", header: "x-csrftoken" },
  },
  // The headers of the request being served that the API should see
  forward: { requestId: true, trace: true, clientAddress: true },
  endpoints: {
    me: endpoint.get("me").response<{ id: string; name: string }>(),
    rename: endpoint.post("me/name").variables<{ name: string }>(),
    signOut: endpoint.post("logout", { session: "unguarded" }),
    catalog: endpoint.get("catalog", { session: false, forward: false }),
  },
})

session

OptionWhat it does
cookiesThe cookies the session is kept in: names, matched exactly as browsers keep them, or prefixes written with a trailing * — "logto_*" matches logto_app and logto_ref. Only these are sent.
bearerA cookie holding a token the API takes as Authorization: Bearer <token>. The cookie itself is sent only when cookies names it too.
csrfThe double-submit token: the cookie it is kept in, sent with the session, the header a write repeats it in, and from, where the API hands it out — see When there is no token yet.
relayPass the session cookies the API sets back to the browser — default true.
allowedOriginsPages on other origins whose requests may make writes with the session, written as the proxy's allowedOrigins are.
allowHttpSend the session over plain HTTP to a host on the public internet. Left unset, it travels only over HTTPS or to a private host.

forward

The headers of the request being served that the API should see: its id, so each API's logs join your application's; the W3C trace context; the user's address, browser and languages; and further headers by name — never a credential, a connection header or a header that claims a client's address, which a request could have written itself. Each option is listed under forward, and the user's address is told in full in The user's address.

Where a call takes it from

Courier finds the request being served as a call starts, before it first waits — some frameworks know the request only until then — and reads it when the call is sent.

Where the call is madeWhat it carries
Server code while a framework serves a requestThe session from that request, found by the framework's adapter — see the setup per framework
The proxy route, for a browser's callThe session from the browser's request to the proxy
A proxy caller in server code, such as universal code rendering a pageThe proxy in the same process, with the session of the user the page is for — no request leaves the server
Server code that names a request: createCaller(api, { context: { req } })The session from that request
A browserIts own cookies, sent by the browser, which the call asks for with credentials: "include" — see an API on another site
A React Native appIts own cookies, sent by the platform as a browser sends them; what a page would read from document.cookie is kept from the API's answers — see React Native
Server code with no request — a script, a cron job, a buildNothing

A call of the server's caller asks the platform's fetch to send no credentials of its own, credentials: "omit", whatever the API's options name, and so do one an MCP server makes for an agent and one the proxy's handler makes for a page, a stream it relays among them: on a server with a DOM on its global object — a test that runs server code under jsdom, say — no fetch that keeps a page's cookies sends them with it. It carries the session it reads of a request in its headers.

A header the call sets itself — in a caller's headers, or with .with({ headers }) — wins over the one the session would send.

Framework setup

Next.js — lib/api.server.ts
import { createServerCaller } from "@noverax/courier-next"
import { api } from "@/api"

// Pages, layouts, Server Actions and Route Handlers call through it
export const server = createServerCaller(api)
SvelteKit 2.20+ — src/hooks.server.ts
import { getRequestEvent } from "$app/server"
import { registerRequestContext } from "@noverax/courier/server"
import { svelteKitRequestContext } from "@noverax/courier-sveltekit"

registerRequestContext(svelteKitRequestContext(getRequestEvent))
SvelteKit, any 2.x — src/hooks.server.ts
import { requestContextHandle } from "@noverax/courier-sveltekit/handle"

export const handle = requestContextHandle()
Nuxt 3 and 4 — server/plugins/courier-request.ts
import { requestContextPlugin } from "@noverax/courier-nuxt"

export default defineNitroPlugin(requestContextPlugin)
Express — app.ts
import { requestContext } from "@noverax/courier-express"

app.use(requestContext())
Fastify 4 and 5 — server.ts
import { requestContext } from "@noverax/courier-fastify"

app.addHook("onRequest", requestContext())
Hono 4 — src/index.ts
import { requestContext } from "@noverax/courier-hono/request-context"

app.use(requestContext())
Astro 5 — src/middleware.ts
import { requestContext } from "@noverax/courier-astro/request-context"

export const onRequest = requestContext()
React Router 7 and 8 — app/root.tsx
import { requestContext } from "@noverax/courier-remix/request-context"

export const middleware = [requestContext()]
Remix v2 — server.js, before Remix's handler
import { requestContext } from "@noverax/courier-express"

app.use(requestContext())
app.all("*", createRequestHandler({ build }))
SolidStart 1 and 2 — src/entry-server.tsx
import { registerRequestContext } from "@noverax/courier/server"
import { solidStartRequestContext } from "@noverax/courier-solid"
import { getRequestEvent } from "solid-js/web"

registerRequestContext(solidStartRequestContext(getRequestEvent))
TanStack Start 1 — src/start.ts
import { createCsrfMiddleware, createMiddleware, createStart } from "@tanstack/react-start"
import { requestContext } from "@noverax/courier-tanstack-start/react"

export const startInstance = createStart(() => ({
  requestMiddleware: [
    createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === "serverFn" }),
    createMiddleware().server(requestContext()),
  ],
}))
NestJS 10 to 12, Express or Fastify — src/main.ts
import { requestContext } from "@noverax/courier-nestjs"

const app = await NestFactory.create(AppModule)
app.use(requestContext())

What Next.js does differently — a Server Action, the Pages Router, a page built ahead of time — is on Next.js. Any other Node server serves a request with withIncomingRequest(nodeIncomingRequest(req, res), next) from @noverax/courier/node; another framework registers a provider of its own with registerRequestContext.

What a call sends

  • The cookies cookies names, and the double-submit cookie — never the rest of your application's cookies — as the request holds them when the call is made: as the browser sent them, with each the API set or deleted for an earlier call. On Next.js, SvelteKit and Astro, whose cookies hold a request's cookies, one your code sets or deletes reaches the calls made after it, and one the API set goes as the API wrote it until your code changes it again: see Next.js, SvelteKit and Astro. On another framework, a cookie your code sets reaches the API with the browser's next request.
  • Authorization: Bearer with the bearer cookie's token, decoded where your framework's cookie API URL-encoded it.
  • The double-submit token on every verb a CSRF check guards — POST, PUT, PATCH, DELETE — and not on reads.
  • Referer set to your application's origin, where csrf is set: Django and Laravel Sanctum take a call for one of your pages only when it names one.
  • The headers forward names.

A session travels only over HTTPS, or to a private host — the local machine, a private network, a cluster's http://api:8080 — and only to the API's origin: a request that an endpoint's absolute URL, or a .via() closure, would take to another host is refused with SESSION_OTHER_ORIGIN before it is sent. Its redirects stay on that origin too, so the credentials never reach a host the API sent the call on to. Give a host of another origin an API of its own, or the endpoint { session: false }.

When there is no token yet

A user the API has not handed the double-submit token yet — on a first visit, signing in, or in a React Native app started again — would send a write without it, and the API would refuse it. Name where the API hands the token out, and a write that finds none asks there first:

api/index.ts
import { courier, defineApi } from "@noverax/courier/define"

const { endpoint } = courier()

export const api = defineApi({
  name: "api",
  baseURL: process.env.API_URL!,
  session: {
    cookies: ["laravel_session"],
    csrf: { cookie: "XSRF-TOKEN", header: "X-XSRF-TOKEN", from: "/sanctum/csrf-cookie" },
  },
  endpoints: {
    signIn: endpoint.post("login").variables<{ email: string; password: string }>(),
  },
})
  • from is a path under the API's baseURL, such as "csrf/" for a Django view decorated with ensure_csrf_cookie, or one from the root of its origin, such as Laravel Sanctum's "/sanctum/csrf-cookie".
  • The GET goes as the API's calls go — its address, headers, fetch and middleware — with the user's session, and only before a write that finds no token: a read repeats none, and a write that finds one asks for nothing. The writes waiting on one user's token share one request.
  • Middleware sees the request with purpose: "csrf-token", its method naming no endpoint, so a middleware that signs every call signs it too, and one meant for endpoints alone can pass it by. A cache keeps none of its answers, and Studio lists it as a request of its own, made within the time of the write that waits for it.
  • On a server, the token reaches the write and the user's browser, as any cookie the API sets does; a browser keeps it itself; a React Native app keeps it from the answer.
  • A request that fails, or an answer that sets no token the call can read, leaves the write to go without it, and the log says so.

Up front

A page whose writes come later — from the browser, or while it renders — can ask for the token as it is served, as Django's ensure_csrf_cookie does. ensureCsrfToken(api) asks once, as a write would, where the request does not carry the token — a cookie of its name that is empty, or holds no token, carries none, as a write reads it — and the token reaches the browser with the response being prepared:

server.ts
import { ensureCsrfToken } from "@noverax/courier/server"
import { api } from "./api"

app.get("/account", async (_req, res) => {
  await ensureCsrfToken(api)
  res.send(renderAccountPage())
})

It needs a request being served, as every server-side call does, and answers whether the request carries the token then; served for another site's link, it asks too, since a token decides no write. A Next.js page cannot set cookies while it renders, so Next.js asks in a middleware: see Next.js.

The cookies the API sets

When the API renews the session, or ends it on signing out, its cookies are carried on — from an error answer as from a success:

  • The calls still to come for the same request send the new value at once.
  • The browser is handed them on the response being prepared, made for your application's origin: set for every path, since the API's path names its own routes; a Domain kept only where it covers your host; Secure over HTTPS, and on the local machine only where the API set it, as WebKit on Linux keeps no secure cookie for http://localhost; elsewhere it is dropped, and SameSite=None becomes Lax. A __Host- or __Secure- cookie your origin cannot keep is not handed over, and the log says why, as it does when a page that has already started streaming can no longer set a cookie.

Cookies the session does not name stay with the API. Set relay: false to keep even the session's own within the request. SvelteKit, Nuxt and Express hand every cookie over as the API wrote it. What Next.js lets a response carry is on Next.js.

An API on another site

A page's calls go with the cookies the browser keeps for the API, as far as the page's site lets them. An API on another origin of the page's site, api.example.com for a page on app.example.com or another port of the same host, gets them in every browser. An API on another site, another domain or 127.0.0.1 for a page on localhost, gets them only where the browser lets a third party keep cookies:

  • Safari keeps none for it.
  • Chrome and Firefox keep the ones it sets SameSite=None; Secure, none where the user blocks third-party cookies, and Firefox keeps them apart for each site that calls it.

Either way, the API answers the page's origin with Access-Control-Allow-Origin naming it and Access-Control-Allow-Credentials: true. A double-submit token is a cookie the page reads, so the API sets it where the page can read it, for its host or a parent domain such as Domain=example.com; a page cannot read another site's cookies, and a write then goes without its token, which the log says.

Courier says once, in the browser's console, when an API that keeps its session in cookies is on another site than the page. Serve the API on the page's site, under a subdomain, or call it through the proxy, which carries the session with the application's own requests.

Writes another site sets off

A page on another site can make the user's browser request one of your pages, with the user's cookies on it. A write made then with the session acts for the user without their asking — the request forgery the API's own defences exist to stop, which the session would otherwise walk past. So a write the session or its double-submit token vouches for is refused with 403, and never sent, unless the request being served is one of your application's own:

  • a form, a Server Action or a fetch — POST and the like — passes the proxy's origin rule: Sec-Fetch-Site says same-origin, or its Origin is your application's, or it is no browser's request at all;
  • a page — GET and the like, which any link can request — has to be one the browser says came from your application, or one the user opened themselves. A browser too old to send Sec-Fetch-Site has to name one of your pages as its Referer.

An origin in session.allowedOrigins counts as your application's own; with none listed, so does another port of the local machine in development, while your application is served from that machine too. A sign-in is guarded too, before anyone has a session: the double-submit token vouches for it, and so does the token a write would ask for — such a write is refused before anything is asked.

The log says why a write was refused, and Studio lists it, ended by its 403 and the reason.

A write that does no harm when someone else sets it off — signing out from a link — says so with session: "unguarded".

A read sent over POST — a GraphQL query, a search, an endpoint declared .reads() — is a read here: it goes with the double-submit token, which the API asks of every POST, and a page reached from another site's link still loads with it. Declare an endpoint a read only when it changes nothing: a write declared one is made for another site's link too, with the user's session and their token. How Next.js tells a page from a write is on Next.js.

Calls that answer everyone alike

An endpoint with session: false is called without the session, and a call to it does not read the request at all: a page that makes only such calls can be built once, and a call can run inside "use cache" or a build. forward: false keeps the forwarded headers off an endpoint's calls likewise.

Streams and channels

A stream or a channel of an API with a session carries the user's session as a read over HTTP does — the cookies cookies names, the bearer, the headers forward names — and the API's own headers, read anew on every connection, so a reconnect sends the token the user has now.

FromA stream's connectionsA channel's socket, on every reconnect too
A serverSend the session taken from the request being served when the stream was opened, and the cookies its answer sets reach the browser as a call's doCarries it on the handshake, taken from the request being served when the channel is opened. A socket is kept to that request: one request's channels share it, and two users' channels never share one
A browserAsk the browser to send its cookies — credentials: "include", unless the API sets credentials itself — and send the bearer the page readsHas the platform send the session's cookies on the handshake itself, as it sends them with a call. A page cannot put a header on the handshake, so the bearer and the API's headers go in its first frame, which the server reads as the handshake's own — see Who a connection is
A React Native appSend the app's cookies and the bearer the app's calls have learned, and learn what the stream's answer setsCarries the platform's cookies on the handshake, and the bearer and the API's headers beside them
The proxy, relaying itOpened upstream with the session of the browser that opened it; a proxy caller sends the browser's cookies to the proxy route with its streams as with its callsOpened upstream with the session of the browser that subscribed, the headers allowedHeaders lets through and those the middleware set, as a relayed call is. One user's subscriptions share an upstream socket; no two users' do

A channel that has not found the request being served in 15 s — a framework's request context that never answers — ends with a ConnectionError: the request is found once, as the channel is opened, and waiting longer would not find it.

A channel repeats no double-submit token: the server checks a socket's origin as it opens, so a page on another site cannot open one on the user's behalf.

Caching

cacheMiddleware({ scope: "public" }) never answers a call that carries the user's session from its shared copy, nor stores its answer, and scope: "session" gives each set of credentials a call sends a partition of its own — in a browser and a React Native app too, where the platform sends the session's cookies. See the cache middleware.

Where a session is checked

A session that could not work as written is refused with a ConfigurationError before any call, whatever NODE_ENV says, on every way a server calls the API with a request: as its sources are registered, as a handler is made with them — the proxy route's, a socket's, the MCP server's — as the server's caller or a Server Action is made, as ensureCsrfToken gives a page its token, and at the first call the server lends a request's session to, whichever caller made it. The codes are listed under session.

A page and a React Native app check, as each call goes, that it would not carry the session over plain HTTP across the public internet: such a call is refused with SESSION_INSECURE_TRANSPORT before anything is sent, unless allowHttp is set. An address on the machine or on a private network is not across the internet, and the call goes. A page's definitions check none of the rest.

Every caller, a server's, a page's and an app's, checks each request of a call that takes the session as it goes: one sent to another origin than the API's is refused with SESSION_OTHER_ORIGIN before it is sent.

A call of an API that keeps a session or forwards headers, whose context names the request it serves, cannot go without the server's part. Made with the caller of @noverax/courier/client in a process where nothing lent it — no handler made, no sources registered, no server's caller made — it is refused with ConfigurationError SERVER_CAPABILITY_MISSING, naming the endpoint, rather than sent without the user's credentials. Make server code's caller with createCaller from @noverax/courier/server, or register the framework's request context with registerRequestContext. The refusal says so, and adds what else it finds: code built for a page, or another copy of the core of another version in the process, which npm ls @noverax/courier, pnpm why @noverax/courier or yarn why @noverax/courier shows.

Next Steps