Next.js SDK
Middleware and helpers for Next.js applications.
The Next.js SDK (@zitadel/sdk-next) is middleware for App Router apps. It proxies /__nextgen/* to Zitadel on your app's origin and validates the session on each request. Server components read the signed-in user with auth().
Generated setup
Let the CLI generate this setup first. Use the manual setup to review or adapt the generated files.
Prerequisites
- Node.js 24 or newer. Run
node --versionto check. - Next.js 15.2.3 or newer with the App Router, and React 18 or newer. Setup does not support the Pages Router.
- A Zitadel project from
zitadel setup. Start the local runtime withnpx @zitadel/cli@latest start, then runnpx @zitadel/cli@latest setup --server localin your app's directory. See the Quickstart, or Add Zitadel to an existing app. - The URL, project ID and project secret. Setup writes them to
.env.localasZITADEL_URL,ZITADEL_PROJECT_ID,ZITADEL_PROJECT_SECRETandNEXT_PUBLIC_ZITADEL_PROJECT_ID.
Install the SDK
Setup installs the SDK. To add it yourself, run:
pnpm add @zitadel/sdk-next@latestWire the SDK into your app
The CLI adds the SDK package, creates auth routes, writes a profile page, and adds the request boundary, the file Next.js runs before each matching request, that runs zitadelMiddleware: proxy.ts when the next version in package.json is 16 or later, otherwise middleware.ts (also for a tag such as latest). With a src/app directory, the pages, the request boundary, and custom-elements.d.ts go under src/; the .env files and package.json stay at the project root.
Every setup also writes zitadel.json and the .zitadel/ folder, adds its entries to .gitignore, and adds managed sections to AGENTS.md and README.md, and configures an AI agent in .mcp.json (Connect an AI agent). When setup created the app itself, it also replaces app/page.tsx with a redirect to /login, and writes a layout.tsx beside the login, register and profile pages that sets their browser tab titles.
Change the dev port
The project allows one origin, http://localhost:<port>, so setup pins the dev script to that port: next dev --port 3000. When the port is taken, next dev exits with EADDRINUSE instead of moving to another port the project does not allow. To run the app on another port, run setup again in the app with the port you want:
npx @zitadel/cli@latest setup --dev-port 3101It allows the new origin on the server, then moves the dev script, ZITADEL_ISSUER in .env.local and zitadel.json to the new port. If the server refuses, nothing changes. Restart the dev server and open http://localhost:3101/login. A social sign-in provider has the redirect URI registered with the old port: the command prints the new one to add at the provider.
Don't change the port in only one of these places. Starting the app with PORT=3101 or npm run dev -- --port 3101 leaves ZITADEL_ISSUER and the allowed origin on the old port, and sign-in breaks.
What the middleware does on each request
/__nextgen/* requests to the Zitadel backend.GET /sessions/me. On any other route, auth() validates it when the page reads the session, so a page that never reads it costs no call to the backend.loginPath, with the requested path and query string in ?next=, where the login component returns after sign-in.Protect a route
To protect another route, add it to protectedRoutes in proxy.ts:
export function proxy(req: NextRequest) {
return zitadelMiddleware(req, {
url: process.env.ZITADEL_URL,
protectedRoutes: ["/profile", "/orders*"],
loginPath: "/login",
});
}A protectedRoutes entry with a trailing * matches every path that starts with it.
The matcher that setup writes covers every route but Next.js's build files, so protectedRoutes alone decides. Next.js runs the middleware only on routes the matcher covers: if you narrow it to a list of routes, a protected route it leaves out is never redirected and stays public.
Read the session in a server component
Read auth state in a server component:
import { auth } from "@zitadel/sdk-next/server";
import { Suspense } from "react";
export default function Page() {
return (
<Suspense fallback={<p>Loading…</p>}>
<Greeting />
</Suspense>
);
}
async function Greeting() {
const session = await auth();
if (!session.isAuthenticated) return <p>Not signed in</p>;
const { display, identifier, userId } = session.session;
return <p>Hello {display ?? identifier ?? userId}</p>;
}auth() reads the request, so the component that calls it renders inside <Suspense>: with Cache Components on, which create-next-app enables, Next.js refuses request data outside it.
auth() sees a session only on routes the middleware's matcher covers. The matcher that setup writes covers every page; a narrower one has to include the page's route, for example "/dashboard/:path*".
Component events
Each component event reaches the callback in the last column. The callback receives the event's detail payload.
| Event | Fires when | Detail | Components | Callback |
|---|---|---|---|---|
zitadel-flow-step | Login shows a step, including the first one. | { step } | Login | onFlowStep |
zitadel-flow-input | The visitor edits a field. | { name, value } | Login | onFlowInput |
zitadel-flow-complete | The flow reaches a terminal step. | { behavior, redirect_uri?, handoff_token?, handoff_token_expires_at? } | Login | onFlowComplete |
zitadel-flow-redirect | The component hands the browser to an identity provider. Nobody is signed in yet. | { redirect_url, step } | Login | onFlowRedirect |
zitadel-flow-error | The flow reports an error. | { message } | Login | onFlowError |
zitadel-signout | The user signs out. | { display, identifier } | Logout, Session | onSignout |
zitadel-session-error | Loading the session or signing out failed, other than with no session. | { status?, code?, message, phase } | Logout, Session | onSessionError |
<ZitadelLogin project={project} theme="light" onFlowComplete={(detail) => track(detail)} />Check that sign-in works
- Run
npm run dev. The app reads the environment that setup wrote to.env.local. - Open
/registeron the dev server, usuallyhttp://localhost:3000/register. Use the origin that setup registered:localhost, not127.0.0.1. - Register a user. A completed sign-in lands on
/profile. - Confirm
/profileshows the signed-in state. - Sign out and confirm
/profileredirects back to/login.
See also
- SDK proxy: why
/__nextgen/*must be same-origin and which call carries the project secret. apps/demo-next: a runnable Next.js example in this repo.@zitadel/sdk-nextsource.
Was this helpful?