Next.js is a React framework for building full-stack web applications. This example demonstrates how to integrate Zitadel using the OAuth 2.0 PKCE flow to authenticate users securely and maintain sessions across your Next.js application.
This example uses next-auth with openid-client to implement the OpenID Connect (OIDC) protocol, manage PKCE code challenge generation, perform secure token exchange, and provide session management helpers.
This Next.js application demonstrates a secure authentication flow using Zitadel with the industry-standard PKCE flow. Users start on a public landing page, initiate login via the Zitadel authorization server, and after successful authentication are redirected back to a protected profile page displaying their user information and claims.
The application implements session management using NextAuth.js with a JWT-based session strategy. It includes automatic callback handling with secure token exchange, route protection for authenticated-only pages, and an example of requesting additional OIDC scopes (including offline_access for refresh tokens and Zitadel-specific scopes for metadata and roles).
The logout flow implements federated logout via the end-session endpoint, terminating both the local session and the Zitadel session before redirecting the user back to the application. It also demonstrates automatic token refresh to maintain long-lived sessions without requiring users to re-authenticate.
Optionally enable refresh tokens in Token Settings for long-lived sessions
Note: Make sure to enable Dev Mode in the Zitadel Console if you're using HTTP URLs during local development. For production deployments, always use HTTPS URLs and disable Dev Mode.
Create a .env.local file (copy from .env.example) and configure it with the values from your Zitadel application. Use these environment variable names exactly as shown:
The Client ID you copied when creating the application
A randomly generated SESSION_SECRET using: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
A randomly generated ZITADEL_CLIENT_SECRET (required by Auth.js / NextAuth.js even though PKCE doesn't require it)
The redirect URIs you configured in the PKCE setup (must match exactly)
Install dependencies using npm by running npm install, then start the development server with npm run dev to verify the authentication flow end-to-end at http://localhost:3000.