Docs

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 --version to 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 with npx @zitadel/cli@latest start, then run npx @zitadel/cli@latest setup --server local in 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.local as ZITADEL_URL, ZITADEL_PROJECT_ID, ZITADEL_PROJECT_SECRET and NEXT_PUBLIC_ZITADEL_PROJECT_ID.

Install the SDK

Setup installs the SDK. To add it yourself, run:

pnpm add @zitadel/sdk-next@latest

Wire 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.

app/login/page.tsx
app/register/page.tsx
app/profile/page.tsx
proxy.ts
custom-elements.d.ts
.env.local
.env.example
package.json

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 3101

It 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

Proxy /__nextgen/* requests to the Zitadel backend.
On a protected route, validate the encrypted session token against 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.
Redirect unauthenticated users from protected routes to 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.

EventFires whenDetailComponentsCallback
zitadel-flow-stepLogin shows a step, including the first one.{ step }LoginonFlowStep
zitadel-flow-inputThe visitor edits a field.{ name, value }LoginonFlowInput
zitadel-flow-completeThe flow reaches a terminal step.{ behavior, redirect_uri?, handoff_token?, handoff_token_expires_at? }LoginonFlowComplete
zitadel-flow-redirectThe component hands the browser to an identity provider. Nobody is signed in yet.{ redirect_url, step }LoginonFlowRedirect
zitadel-flow-errorThe flow reports an error.{ message }LoginonFlowError
zitadel-signoutThe user signs out.{ display, identifier }Logout, SessiononSignout
zitadel-session-errorLoading the session or signing out failed, other than with no session.{ status?, code?, message, phase }Logout, SessiononSessionError
<ZitadelLogin project={project} theme="light" onFlowComplete={(detail) => track(detail)} />

Check that sign-in works

  1. Run npm run dev. The app reads the environment that setup wrote to .env.local.
  2. Open /register on the dev server, usually http://localhost:3000/register. Use the origin that setup registered: localhost, not 127.0.0.1.
  3. Register a user. A completed sign-in lands on /profile.
  4. Confirm /profile shows the signed-in state.
  5. Sign out and confirm /profile redirects back to /login.

See also

Was this helpful?