Fastify is a fast and low overhead web framework for Node.js, designed for building efficient server-side applications. This example demonstrates how to integrate Zitadel using the OAuth 2.0 PKCE flow to authenticate users securely and maintain sessions across your application.
This example shows a complete authentication implementation using Fastify with server-side rendering via @fastify/view and Handlebars templates. The application implements secure user authentication through Zitadel using the industry-standard PKCE flow, which prevents authorization code interception attacks without requiring client secrets.
The example includes a custom sign-in page that initiates the OAuth 2.0 authentication flow, automatic callback handling authentication flow, automatic callback handling with secure token exchange, and JWT-based session management with @fastify/cookie authentication flow, automatic callback handling with secure token exchange, and JWT-based session management with @fastify/cookie. Protected routes use the requireAuth middleware to automatically redirect unauthenticated users to the sign-in flow, ensuring only authenticated users can access sensitive areas. The profile page displays comprehensive user information including OIDC claims authentication flow, automatic callback handling with secure token exchange, and JWT-based session management with @fastify/cookie. Protected routes use the requireAuth middleware to automatically redirect unauthenticated users to the sign-in flow, ensuring only authenticated users can access sensitive areas. The profile page displays comprehensive user information including OIDC claims and session metadata.
The application also demonstrates proper federated logout by terminating sessions both locally and with Zitadel's end-session endpoint, complete with CSRF protection using state parameters. Additionally, it includes automatic token refresh using refresh tokens to maintain long-lived sessions without requiring users to re-authenticate. The example uses Zitadel-specific scopes like urn:zitadel:iam:user:metadata and urn:zitadel:iam:org:projects:roles to access extended user attributes and role information for implementing role-based access control (RBAC).
Before running this example, you need to create and configure a PKCE application in the ZITADEL Management Console. Follow the PKCE application setup guide to:
Optionally enable refresh tokens in Token Settings for long-lived sessions
Note: Make sure to enable Dev Mode in the ZITADEL Management Console if you're using HTTP URLs during local development. For production, always use HTTPS URLs and disable Dev Mode.
Create a .env file (copy from .env.example) and configure it with the values from your Zitadel application. Use these exact environment variable names: