Courier has first-class Next.js support through the @noverax/courier-next package. It covers every Next.js pattern: API routes, client components with React Query, server components, and server actions.
WebSockets require a standalone server
Next.js App Router cannot host WebSocket upgrades in-process — neither RSC nor route handlers expose the underlying TCP socket. If your API uses WS endpoints, run @noverax/courier-server alongside Next.js and point proxyPath.ws at it (e.g. ws://localhost:3001 in dev, wss://realtime.example.com in prod). HTTP and SSE continue to work in-process via the App Router.
In one command
npx @noverax/create-courierIn a Next.js app it adds what this page sets up by hand — the API route, the registration in instrumentation.ts and Studio's connection on both sides — with a typed example API, its mock, and a page at /courier. See Create Courier.
Studio integration & appOrigin
Wire your Next.js app into Studio with an attachRuntime() call in the register() of instrumentation.ts — the same function that registers your sources (Step 1). Connect the server says what it does. The appOrigin field — where the Playground sends its proxy calls — lives in courier.config.ts.runtime.appOrigin (or set the COURIER_APP_URL env var to override per-environment).
import { registerSources } from "@noverax/courier/server"
export async function register() {
const { sources } = await import("./lib/sources")
registerSources(sources)
if (process.env.NEXT_RUNTIME !== "nodejs") return;
if (process.env.NODE_ENV !== "development") return;
const { attachRuntime } = await import("@noverax/courier-studio-core/runtime");
await attachRuntime();
}Alternatively, set the COURIER_APP_URL environment variable instead of pinning appOrigin in the config:
COURIER_APP_URL=http://localhost:3000 next devWithout either, in development the app learns its origin from next dev itself, before any request, whatever name or proxy it is reached by — see How the app learns its origin.
That connects the server. To see requests the browser makes, connect it too, from instrumentation-client.ts (Next.js 15.3 and later, under Turbopack or webpack):
import { attachRuntime } from "@noverax/courier-studio-core/runtime";
if (process.env.NODE_ENV === "development") {
attachRuntime("next-browser");
}A browser bundle cannot read courier.config.ts: if Studio is not at its default address, add env: { COURIER_STUDIO_URL: "http://localhost:6290" } to next.config.ts. Under webpack, withCourierStudio() from @noverax/courier-studio/next connects the browser without the file, and keeps ws, which the server's Studio connection runs on, out of the server bundle; bundled, ws fails on every frame of 48 bytes or more and the server never reaches Studio. Under webpack without the wrapper, add serverExternalPackages: ["ws"] to next.config.ts.
next start loads next.config too, and Studio is a dev dependency, which an install for production leaves out. Import the wrapper in next dev alone:
import type { NextConfig } from "next"
const nextConfig: NextConfig = {}
export default async function config(phase: string): Promise<NextConfig> {
// PHASE_DEVELOPMENT_SERVER: next dev alone loads Studio, a dev dependency
if (phase !== "phase-development-server") return nextConfig
const { withCourierStudio } = await import("@noverax/courier-studio/next")
return withCourierStudio()(nextConfig)
}In a next.config.mjs, leave out the types; the phase is written out because an ES module config of Next.js 14 cannot import next/constants.
Installation
npm install @noverax/courier @noverax/courier-next @noverax/courier-react @tanstack/react-queryDefine your API sources
Create the API definition the server's callers, the proxy route and Studio share. A page never imports it: it takes the routes Courier's plugin builds from it, so the definition stays out of the browser bundle.
import { courier, defineApi, defineGroup } from "@noverax/courier/define"
const { endpoint } = courier()
type User = { id: number; name: string; email: string }
type UserList = { data: User[]; total: number }
const users = defineGroup({
prefix: "users",
// A page may call these through the proxy; an endpoint no mark opens stays the server's
expose: true,
endpoints: {
getAll: endpoint.get("").variables<{ page?: number; limit?: number }>().response<UserList>(),
getById: endpoint.get(":id").variables<{ id: number }>().response<User>(),
create: endpoint.post("").variables<{ name: string; email: string }>().response<User>(),
update: endpoint.put(":id").variables<{ id: number; name: string; email: string }>().response<User>(),
remove: endpoint.del(":id").variables<{ id: number }>().response<null>(),
},
})
export const api = defineApi({
baseURL: process.env.API_URL ?? "http://localhost:4000",
groups: { users },
})
export const sources = { myApi: api }Step 1: API Route
Create a Next.js App Router route handler that proxies browser requests to your backend, and register your sources at server start. Without Studio, this is the whole of instrumentation.ts; with it, use the register() under Studio integration, which does the same and attaches the runtime in development:
import { registerSources } from "@noverax/courier/server"
export async function register() {
const { sources } = await import("./lib/sources")
registerSources(sources)
}import { apiRoute } from "@noverax/courier-next"
export const { GET, POST } = apiRoute()The names your app is reached by
next build runs the route module while it collects page data, where your deployment's variables are not set yet. Name the hosts the app is reached by with a function, which the route calls when the first request comes in, or with COURIER_ALLOWED_HOSTS on the deployment:
import { apiRoute } from "@noverax/courier-next"
export const { GET, POST } = apiRoute({
allowedHosts: () => [new URL(process.env.APP_URL!).host],
})Read a server variable there, not a NEXT_PUBLIC_ one: Next.js writes those into the code as it builds, so the function would return the build's host. allowedOrigins takes a function too, and COURIER_ALLOWED_ORIGINS. See Names known where the app runs.
Next.js runs instrumentation.ts once at server start, populating the core global registry that apiRoute() reads at request time. register() runs once in each runtime the app uses, and each runtime has its own registry: a route with export const runtime = "edge" reads the Edge runtime's, so the sources are registered in both. If your sources module imports Node-only code, register an Edge-safe one when process.env.NEXT_RUNTIME === "edge". sseRoute() streams in the Edge Runtime as well as in Node.js. The route handles all Courier proxy requests — parses the incoming POST body, resolves the correct endpoint, calls your backend, and returns the response.
The user's address
Next.js tells a route no connection, so the user's address a call tells an API, and a rate limit counts a caller by, is read from X-Forwarded-For as the proxy in front recorded it. Next.js writes the connection's address there only into a request that carries none, and keeps one the user wrote: serve the app behind a proxy that appends the address it saw, or a platform that writes the header itself. See The user's address.
Uploads and proxy.ts
The route reads a JSON call up to its maxBodyBytes, 1 MB, and an upload up to its maxUploadBytes, 10 MB; pass others to raise them: apiRoute({ maxUploadBytes: 50 * 1024 * 1024 }).
A proxy (proxy.ts, or middleware.ts before Next.js 16) that runs on the route sets a limit of its own. Next.js copies the request's body for the proxy and hands the route only its first experimental.proxyClientMaxBodySize bytes, 10 MB unless configured — experimental.middlewareClientMaxBodySize in Next.js 15 — while the request keeps the length the browser declared. The route checks the body against that length, so a larger upload is answered 413 with the code BODY_INCOMPLETE and a message that names the setting, rather than reaching your backend cut short. A matcher such as the one Next.js suggests, every path but its own assets, covers the route. Leave the route out of the proxy's matcher:
export const config = { matcher: ["/((?!api/request|_next/static|_next/image|favicon.ico).*)"] }Or raise the proxy's limit above the route's maxUploadBytes, which keeps a copy of each body that large in memory while the proxy runs:
import { withCourier } from "@noverax/courier-next/plugin"
export default withCourier({ experimental: { proxyClientMaxBodySize: "60mb" } })Next.js 14 copies the whole body for its middleware, whatever its size, and cuts nothing short.
Next.js reads a route's request body as fast as the browser sends it, whatever the route has taken. An upload sent on as it arrives (uploadMode: "stream") behind a backend slower than the browser therefore waits in Next.js's memory for the backend to take it.
Step 2: Client-side caller (React Query)
List your sources in courier.config.ts, and pass your Next.js config to withCourier(): from the endpoints the sources mark .expose(), Courier's plugin builds in the routes a page's caller takes, under Turbopack and webpack alike — see Exposing Endpoints. It runs on @noverax/courier-build, which next start loads with next.config, so install it as a dependency:
npm install @noverax/courier-buildimport { defineConfig } from "@noverax/courier/config"
import { sources } from "./lib/sources"
export default defineConfig({ sources })import type { NextConfig } from "next"
import { withCourier } from "@noverax/courier-next/plugin"
const nextConfig: NextConfig = {}
export default withCourier(nextConfig)Create a query caller for use in client components, from the routes of myApi, in a module that registers the config, so they are typed from it:
import { createProxyQueryCaller } from "@noverax/courier-react"
import { routes } from "@noverax/courier/routes"
import type config from "../courier.config"
declare module "@noverax/courier/routes" {
interface Register {
config: typeof config
}
}
export const q = createProxyQueryCaller(routes.myApi)A project that takes courier.routes.ts moves to the plugin with npx @noverax/courier-cli setup; one that would keep the file writes it with npx @noverax/courier-cli routes, and gives the caller myApiRoutes from it in place of routes.myApi.
Use it in client components:
"use client"
import { q } from "@/lib/query"
export default function UsersPage() {
const { data, isLoading } = q.users.useQuery("getAll", {
variables: { page: 1, limit: 10 },
})
const { mutate, isPending } = q.users.useMutation("create", {
onSuccess: (user) => {
console.log("Created:", user.name) // fully typed
},
})
if (isLoading) return <p>Loading...</p>
return (
<div>
<h1>Users ({data?.total})</h1>
<ul>
{data?.data.map((user) => (
<li key={user.id}>{user.name} — {user.email}</li>
))}
</ul>
<button
onClick={() => mutate({ name: "Jane", email: "jane@test.com" })}
disabled={isPending}
>
Add User
</button>
</div>
)
}QueryClientProvider
Wrap your app with QueryClientProvider in your root layout. See the React Query setup page for details.
Step 3: Server Components (createServerCaller)
For React Server Components, use createServerCaller to call your backend directly without the proxy hop:
import { createServerCaller } from "@noverax/courier-next"
import { api } from "@/lib/sources"
export const caller = createServerCaller(api)It is createCaller that also finds the request Next.js is serving: an API that keeps a session gets the user's session from it, and a page whose calls carry one is rendered per request — see the user's session.
import { caller } from "@/lib/server-caller"
export default async function DashboardPage() {
const users = await caller.users.getAll({
page: 1,
limit: 5,
})
return (
<div>
<h1>Dashboard ({users.total} users)</h1>
<ul>
{users.data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
)
}No proxy overhead
createServerCaller calls your backend directly from the server. There is no round-trip through the API route, making it ideal for SSR and RSC.
One read per render
A page often reads the same thing in several places: generateMetadata reads the user for the title, the page reads them for the body, a component reads them again. Within one render, a read that sends the same request again is answered with the first one's answer, however far apart the two are, each caller getting a copy of its own:
import { caller } from "@/lib/server-caller"
type Props = { params: Promise<{ id: string }> }
export async function generateMetadata({ params }: Props) {
const user = await caller.users.getById({ id: Number((await params).id) })
return { title: user.name }
}
export default async function UserPage({ params }: Props) {
// Answered from the read generateMetadata made: the API is asked once
const user = await caller.users.getById({ id: Number((await params).id) })
return <h1>{user.name}</h1>
}The render's reads are kept by React's cache(), so they last one request and are never shared between users. A read is the same only when everything it sends is — the variables, and every header, the user's session cookies among them — so a read made after the API renewed the session goes out with the new cookies. A write made during the render forgets every read, and what is read after it is read anew; a read that failed is not kept, nor one that asks coalesce: false. Route Handlers and Server Actions run outside a render, and each of their reads goes out. Identical reads made at the same moment share one request anywhere — see Deduplication & Abort.
The user's session
Describe the session the API keeps where it is defined, and every server-side call made for a user carries that user's session, the cookies the API keeps it in and nothing else of your application's:
import { courier, defineApi } from "@noverax/courier/define"
const { endpoint } = courier()
export const api = defineApi({
name: "myApi",
baseURL: process.env.API_URL!,
session: { cookies: ["sessionid"], csrf: { cookie: "csrftoken", header: "x-csrftoken" } },
endpoints: {
me: endpoint.get("me").response<{ id: number; name: string }>(),
},
})| Where | How it finds the request |
|---|---|
| Pages, layouts, Route Handlers | createServerCaller(api) registers nextRequestContext as its module loads |
| Server Actions | createAction reads the action's own request; createServerCaller works too |
| Pages Router | withRequestContext from @noverax/courier-next/pages wraps getServerSideProps and API routes |
| Client components | A proxy caller: the proxy route reads the browser's request |
Next.js builds pages ahead of time
Reading the request is what tells Next.js that a page belongs to one user and has to be rendered per request. next build does not run instrumentation.ts, so a provider registered only there finds no request while pages are built: a page whose calls carry the session would be built once, without anyone's, and served to everyone. createServerCaller registers the provider where its caller is made, which a build loads.
| Next.js | What differs | How the session handles it |
|---|---|---|
| 14 | headers() and cookies() answer synchronously; a server's fetch is kept in the data cache by default | Their answer is awaited, which takes either form; a call made for a request is fetched with cache: "no-store" |
| 15 | Both answer with a promise | Awaited |
| 16 | Both answer with a promise alone; with cacheComponents, request data is read under <Suspense> and never inside "use cache" | A component whose calls carry the session goes under <Suspense>, as one reading cookies() itself would, and becomes the page's dynamic part; inside "use cache" such a call fails with Next.js's own error, and an endpoint with session: false is cached as any other call |
In every version, what Next.js stops a render with — a page found to be dynamic, a prerender postponed, a request read inside a cache — reaches Next.js as it came, and a build, a script or generateStaticParams finds no request and sends no session.
Each call that carries the session sends the user's cookies as cookies() holds them when it is made — those a middleware set, and those a Server Action or a Route Handler set or deleted before it, included — and a cookie the request carried that nothing changed goes as it came. A cookie the API sets or deletes goes as the API wrote it with the calls that follow, until your code changes it again.
The session cookies the API sets reach the browser from a Server Action and a Route Handler. Next.js lets no page set cookies while it renders, so a session the API renews during a render reaches that render's later calls only, and the log says so. Next.js also URL-encodes the value it writes, so a cookie whose value is not already URL-encoded is not handed over through it — relay it through the proxy route instead, which passes cookies on byte for byte.
Next.js does not tell a request's method
A Server Action's request is POST; any other request a Next.js App Router serves is read as a page's. A Route Handler's write for a client that is no browser, and so marks nothing, is refused — such a client authenticates with its own token, not with your users' cookies.
User Sessions covers the options and the writes another site sets off.
A page that writes while it renders
A write the API guards with a double-submit token asks for the token first when the user has none, and a page that renders cannot hand it to the browser: the next render asks again. A middleware hands it over with the page instead, where the request does not carry it, and gives it to the render too, with a session cookie the API renewed as it handed the token out in place of the one the request had:
import { csrfTokenMiddleware } from "@noverax/courier-next/middleware"
import { api } from "@/lib/sources"
export const proxy = csrfTokenMiddleware(api)
export const config = { matcher: ["/account/:path*"] }Before Next.js 16 the file is middleware.ts and the export middleware. Import the API's definition alone there, not a module that makes a server caller. Match the pages that write while they render, or every page whose later writes should find the token waiting. A middleware of your own composes it with handCsrfTokens:
import { handCsrfTokens } from "@noverax/courier-next/middleware"
import { type NextRequest, NextResponse } from "next/server"
import { api } from "@/lib/sources"
export async function proxy(request: NextRequest) {
const tokens = await handCsrfTokens(request, api)
const response = NextResponse.next({ request: { headers: tokens.headers } })
response.headers.set("x-frame-options", "DENY")
return tokens.handTo(response)
}The render gets the tokens through tokens.headers, and the browser each cookie as the API wrote it. Set a cookie of your own there through response.headers, not response.cookies: one set through response.cookies has Next.js rewrite the Cookie the render reads, every value URL-encoded, so a session cookie not already in that form reaches the API changed.
Next.js 14, 15 and 16 are checked with it: the token is asked once, the render's write repeats it with the session's cookies as the browser sent them, or as the token's request renewed them, and the next visit asks nothing.
Step 4: Server Actions (createAction)
Use createAction for type-safe server actions that read the action's own request — its headers, and the session of an API that keeps one:
import { createAction } from "@noverax/courier-next"
import { sources } from "@/lib/sources"
export const action = createAction(sources, "myApi")"use server"
import { revalidatePath } from "next/cache"
import { action } from "@/lib/actions"
export async function createUser(data: { name: string; email: string }) {
const user = await action.users.create(data)
revalidatePath("/users")
return user
}
export async function deleteUser(id: number) {
await action.users.remove({ id })
revalidatePath("/users")
}Use server actions in client components:
"use client"
import { useActionState } from "react"
import { createUser } from "@/app/actions/users"
export function CreateUserForm() {
const [state, formAction, isPending] = useActionState(
async (_prev: unknown, formData: FormData) => {
const result = await createUser({
name: formData.get("name") as string,
email: formData.get("email") as string,
})
return result
},
null
)
return (
<form action={formAction}>
<input name="name" placeholder="Name" required />
<input name="email" type="email" placeholder="Email" required />
<button type="submit" disabled={isPending}>
{isPending ? "Creating..." : "Create User"}
</button>
</form>
)
}Full project structure
courier.config.ts # defineConfig({ sources })
next.config.ts # withCourier(nextConfig): the routes from the .expose() marks
app/
api/request/route.ts # apiRoute()
actions/users.ts # server actions with createAction
users/page.tsx # client component with useQuery
dashboard/page.tsx # server component with createServerCaller
lib/
sources.ts # defineApi + defineGroup + endpoint
query.ts # createProxyQueryCaller(routes.myApi)
server-caller.ts # createServerCaller(api)
actions.ts # createAction(sources, "myApi")Use both modes together
Most Next.js apps use all three: createProxyQueryCaller for client components, createServerCaller for server components, and createAction for server actions. They all share the same source definitions, and the same session.