Keycloak authentication for Next.js gives SaaS teams a way to add secure login, enterprise Single Sign-On (SSO), and multi-factor authentication (MFA) without building an identity system from scratch. The problem is that authentication quickly becomes more involved than adding a login form. You need to manage user sessions, protect application routes, connect external identity providers, and enforce additional security checks.

For a growing SaaS product, maintaining all those pieces can take time away from the features customers actually use. Running an identity platform also introduces infrastructure work, including deployment, updates, availability, and backups.

A managed Keycloak service changes that. Your Next.js application can delegate authentication to Keycloak through OpenID Connect (OIDC), while the managed service takes care of operating the Keycloak infrastructure. Auth.js provides a convenient integration point for the Next.js application, and Keycloak handles the identity flows behind it.

This guide walks through the architecture and the implementation pieces needed to connect them. The examples use the Next.js App Router, Auth.js, and a managed Keycloak instance. They show how login, enterprise SSO, and MFA fit together without requiring your team to host Keycloak itself.

TL;DR

You can add login, enterprise SSO, and MFA to a Next.js SaaS by integrating Auth.js with a managed Keycloak instance through OpenID Connect. Configure a confidential Keycloak client, connect it to Auth.js using the Keycloak provider, and use the resulting application session to protect your routes. Then enable external identity providers in Keycloak for enterprise SSO and configure its authentication flows to require MFA.

The essential pieces are:

  • Next.js: Runs your SaaS application, pages, and protected server-side routes.
  • Auth.js: Handles the authentication integration and application session.
  • Keycloak: Manages user authentication, identity federation, and MFA.
  • Managed Keycloak hosting: Provides the Keycloak environment without requiring your team to deploy and maintain the identity server.

Your application keeps control of its business logic and authorization rules, while Keycloak handles the identity layer.

What the Authentication Architecture Looks Like

Before adding packages or changing your login page, it helps to understand how the components communicate. Next.js does not need to implement password verification, SAML processing, or MFA challenges itself. It redirects users to Keycloak, which handles the authentication process and returns the result through the OIDC authorization flow.

In this setup, Auth.js connects your Next.js application to Keycloak. When someone selects Sign in, the application starts an authentication request. Keycloak displays the login experience, checks the user's credentials, applies the configured authentication requirements, and redirects the browser back to the Auth.js callback URL.

The application then establishes its own session. Protected pages and server-side operations use that session to identify the signed-in user. Your backend remains responsible for deciding what the user can access inside the SaaS product.

The flow looks like this:

  1. The user opens your Next.js application and selects Sign in.
  2. Auth.js redirects the browser to Keycloak.
  3. Keycloak authenticates the user and applies any required MFA steps.
  4. Keycloak redirects the browser to the application's Auth.js callback.
  5. Auth.js completes the OIDC flow and establishes an application session containing the authenticated user's session information.
  6. Next.js uses that session to protect pages and server-side functionality.

This separation keeps the responsibilities clear. Keycloak handles identity verification, Auth.js connects the identity provider to your application, and your SaaS decides what an authenticated user is allowed to do.

Create an OpenID Connect Client in Keycloak

I used Skycloak to provision a managed Keycloak instance without setting up the underlying infrastructure myself. I started by creating a new cluster named nextjs-demo-cluster, which provided the Keycloak environment for the experiment.

Skycloak dashboard showing the nextjs-demo-cluster managed Keycloak cluster with Available status

Creating a managed Keycloak cluster with Skycloak

Skycloak dashboard showing the nextjs-demo-cluster details

nextjs-demo-cluster details page  

After the cluster became available, I opened its details page and selected Open Admin Console to access Keycloak. I then created a dedicated realm named nextjs-demo for the Next.js application. A realm provides an isolated space for managing users, applications, and authentication settings.

Skycloak managed Keycloak Admin Console showing the nextjs-demo realm selected for Next.js authentication

Creating a realm in the Keycloak Admin Console

Realm created successfully

Realm created successfully  

With the realm ready, I opened Clients, selected Create client, chose OpenID Connect as the client type, and entered nextjs-saas as the Client ID. I also used Next.js SaaS as the client name to make it easy to identify in the administration console.

Creating a Keycloak OpenID Connect client named nextjs-saas for a Next.js SaaS application

Registering the Next.js SaaS application as an OpenID Connect client in Keycloak  

For a server-side Next.js application, I enabled Client authentication and Standard flow in the client's capability settings. Client authentication makes the client confidential, allowing Auth.js to use a client secret during the token exchange. Standard flow enables the authorization code flow used by this integration.

Keycloak client capability settings with Client authentication and Standard flow enabled for Next.js Auth.js integration

Enabling confidential client authentication and the standard authorization code flow  

Next, I configured the redirect URI under Valid Redirect URIs. Auth.js uses the following callback path by default:

http://localhost:3000/api/auth/callback/keycloak 

I added this exact address to the Keycloak client configuration. When deploying the application, its production callback URL must also be registered:

https://app.example.com/api/auth/callback/keycloak 

Use the exact URLs for your application environments. Avoid broad wildcard redirect patterns in production because they allow more destinations than the authentication flow requires.

Keycloak Valid Redirect URIs configuration showing the localhost Auth.js callback URL for a Next.js application

Configuring the Auth.js callback URL in the Keycloak client's Valid Redirect URIs  

After saving the client, I opened its Credentials tab and copied the generated client secret. Auth.js needs this value when exchanging authorization codes for tokens, so it must remain private and available only to the server-side application.

Credentials tab

Keycloak client credentials used by the Next.js Auth.js integration  

I also retrieved the realm's issuer URL from its OpenID Connect discovery document. The URL follows this format:

https://your-keycloak-domain.com/realms/your-realm 

For my test configuration, the realm was nextjs-demo, and the issuer URL pointed to that realm on my Skycloak-managed Keycloak instance.

Keycloak OpenID Connect discovery document showing the issuer URL for the nextjs-demo realm hosted on Skycloak

Retrieving the Keycloak realm's OIDC issuer URL from the discovery document  

At this point, the Next.js application has a registered OIDC client, a configured callback URL, and the credentials needed for the Auth.js integration. Keep the client ID, issuer URL, and client secret available for the next step. The client secret must remain on the server and must never be exposed through a NEXT_PUBLIC_ environment variable.

Connect Next.js to Keycloak with Auth.js

With the Keycloak client registered, the Next.js application needs an authentication library to handle the OIDC flow and maintain its application session. Auth.js provides a built-in Keycloak provider, so you don't need to implement the authorization redirects, callback handling, or token exchange yourself.

The examples in this guide use Auth.js v5. Install the v5 beta package with next-auth@beta if v5 is not yet the default release available through next-auth.

npm install next-auth@beta 

Create a .env.local file in the project root and add the Keycloak configuration:

AUTH_SECRET="your-long-random-secret" AUTH_URL="http://localhost:3000" AUTH_KEYCLOAK_ID="nextjs-saas" AUTH_KEYCLOAK_SECRET="your-keycloak-client-secret" AUTH_KEYCLOAK_ISSUER="https://your-keycloak-domain.com/realms/your-realm" 

Replace the example values with the credentials and issuer URL from your Keycloak configuration. Generate a strong random value for AUTH_SECRET; Auth.js uses it to protect its session data and related cryptographic operations.

Now create an auth.ts file at the root of your project:

import NextAuth from "next-auth"; import Keycloak from "next-auth/providers/keycloak"; export const { handlers, auth, signIn, signOut } = NextAuth({ session: { strategy: "jwt", }, providers: [ Keycloak({ clientId: process.env.AUTH_KEYCLOAK_ID!, clientSecret: process.env.AUTH_KEYCLOAK_SECRET!, issuer: process.env.AUTH_KEYCLOAK_ISSUER!, }), ], callbacks: { async jwt({ token, account }) { if (account?.id_token) { token.idToken = account.id_token; } return token; }, async session({ session, token }) { session.idToken = token.idToken as string | undefined; return session; }, async redirect({ url, baseUrl }) { try { const target = new URL(url); const appOrigin = new URL(baseUrl).origin; const keycloakOrigin = new URL( process.env.AUTH_KEYCLOAK_ISSUER! ).origin; if ( target.origin === appOrigin || target.origin === keycloakOrigin ) { return target.toString(); } } catch {} return baseUrl; }, }, }); 

To make the Keycloak ID token available in the session, extend the Auth.js session and JWT types. Create a types/next-auth.d.ts file in your project root and add:

import "next-auth"; import "next-auth/jwt"; declare module "next-auth" { interface Session { idToken?: string; } } declare module "next-auth/jwt" { interface JWT { idToken?: string; } } 

This configuration registers Keycloak as an authentication provider. Auth.js uses the issuer to discover the OIDC endpoints for your realm and the client credentials to communicate with Keycloak during authentication.

Next, expose the Auth.js handlers through the Next.js App Router. Create this file:

app/api/auth/[...nextauth]/route.ts

Add the following code:

import { handlers } from "@/auth"; export const { GET, POST } = handlers; 

These handlers provide the authentication endpoints used by Auth.js, including the sign-in and callback routes. When a user starts a Keycloak login, Auth.js uses these endpoints to manage the OIDC exchange and establish the application session.

At this point, your Next.js application has a connection to Keycloak. The next step is giving users a way to start the login process and protecting the pages that require an authenticated session.

Add Login and Logout to Your Next.js Application

Your authentication configuration is ready, but users still need a way to start and end their sessions. Auth.js provides signIn and signOut helpers for these actions, so you can connect them directly to your application's interface.

For a simple login page, create a server action that starts authentication with the Keycloak provider.

Create app/actions/auth.ts:

"use server"; import { auth, signIn, signOut } from "@/auth"; export async function signInWithKeycloak() { await signIn("keycloak", { redirectTo: "/dashboard", }); } export async function signOutFromApp() { const session = await auth(); const logoutUrl = new URL( `${process.env.AUTH_KEYCLOAK_ISSUER}/protocol/openid-connect/logout` ); if (session?.idToken) { logoutUrl.searchParams.set("id_token_hint", session.idToken); } logoutUrl.searchParams.set( "post_logout_redirect_uri", `${process.env.AUTH_URL}/login` ); await signOut({ redirectTo: logoutUrl.toString(), }); } 

The signIn function redirects the user to Keycloak to complete authentication. After a successful login, Auth.js sends the user to /dashboard. When the user signs out, the application clears its Auth.js session and redirects the browser to Keycloak's logout endpoint. The request includes the ID token through id_token_hint and the application's login page through post_logout_redirect_uri. Keycloak can then end its own session before redirecting the user back to the application.

Now create a login page at app/login/page.tsx:

import { signInWithKeycloak } from "@/app/actions/auth"; export default function LoginPage() { return ( <main> <h1>Welcome back</h1> <p>Sign in to continue to your workspace.</p> <form action={signInWithKeycloak}> <button type="submit"> Sign in with Keycloak </button> </form> </main> ); } 

You can also add a logout button to your dashboard or account menu:

import { signOutFromApp } from "@/app/actions/auth"; export function LogoutButton() { return ( <form action={signOutFromApp}> <button type="submit"> Sign out </button> </form> ); } 

These examples use Server Actions, so the authentication operations run on the server. Your login interface stays simple, while Auth.js handles the redirects and session operations.

Protect Dashboard Pages and Server-Side Resources

A successful login creates an application session, but your SaaS still needs to check that session before showing private content or returning customer data. Auth.js exposes an auth() function that lets Server Components, Route Handlers, and Server Actions retrieve the current session.

For example, create a protected dashboard page at app/dashboard/page.tsx:

import { auth } from "@/auth"; import { redirect } from "next/navigation"; export default async function DashboardPage() { const session = await auth(); if (!session?.user) { redirect("/login"); } return ( <main> <h1>Welcome, {session.user.name}</h1> <p>You are signed in to your workspace.</p> </main> ); } 

The page checks the session on the server before rendering the dashboard. Visitors without an authenticated session are redirected to the login page.

The same principle applies to API endpoints. A protected Route Handler should check the session before returning private information or performing an operation.

For example, create app/api/account/route.ts:

import { auth } from "@/auth"; import { NextResponse } from "next/server"; export async function GET() { const session = await auth(); if (!session?.user) { return NextResponse.json( { error: "Unauthorized" }, { status: 401 } ); } return NextResponse.json({ user: session.user, }); } 

This prevents unauthenticated requests from accessing the endpoint. For operations involving customer data, add authorization checks that confirm the user belongs to the requested organization and has permission to access the resource.

That distinction matters in a multi-tenant SaaS. An active session confirms that someone signed in, but it does not automatically grant access to every workspace, customer record, or administrative action.

For larger applications, centralize these checks in a server-side data access layer. That gives your pages, API endpoints, and Server Actions a consistent way to enforce authentication and organization-level permissions.

Keep the actual authorization checks close to the data and operations they protect. A redirect in a page or a hidden button in the interface should never be the only barrier protecting sensitive functionality.

Add Enterprise SSO with External Identity Providers

Once your application uses Keycloak for authentication, adding enterprise SSO becomes much easier to manage. Keycloak acts as an identity broker, connecting your SaaS to the identity providers that your customers already use, such as Microsoft Entra ID, Okta, and Google Workspace.

The important part is that your Next.js application keeps the same authentication integration. You register each customer's identity provider in Keycloak, and Keycloak handles the communication with that external system. After successful authentication, it returns the user's identity through the existing OIDC flow to Auth.js.

To configure an enterprise connection, open the Keycloak Admin Console and navigate to Identity Providers. Add the provider using its supported protocol:

  • OpenID Connect: Enter the customer's issuer URL, client ID, and client secret. Keycloak uses the provider's discovery document to retrieve its authentication and token endpoints.
  • SAML: Import the customer's identity provider metadata or enter its entity ID, SSO URL, and signing certificate. Share Keycloak's service provider metadata with the customer's IT team so they can register the connection.

Each customer needs its own identity provider configuration. This allows one organization to authenticate through Microsoft Entra ID while another uses Okta, with both connections managed through the same Keycloak realm.

After configuring the connection, test the first login and account-linking behavior. Keycloak's First Broker Login flow handles the creation of a local user or the linking of an external identity to an existing account. Make sure your account-linking rules prevent an untrusted identity provider from claiming an existing user account.

Send users to the correct enterprise identity provider

A SaaS product with multiple enterprise customers also needs a reliable way to identify which organization is signing in. Showing every user the same login page with a long list of identity providers quickly becomes inconvenient.

One option is to give each organization a dedicated login URL, such as:

https://app.example.com/login/acme 

Your Next.js backend resolves the organization and starts the authentication flow with the corresponding Keycloak identity provider.

Keycloak supports the kc_idp_hint parameter for this purpose. Include the identity provider's configured alias in the authorization request:

kc_idp_hint=microsoft-entra 
import { signIn } from "@/auth"; export async function signInWithMicrosoftEntra() { await signIn( "keycloak", { redirectTo: "/dashboard" }, { kc_idp_hint: "microsoft-entra" } ); } 

For a multi-tenant application, resolve the customer's organization on the server and map it to the corresponding trusted Keycloak identity provider alias. Pass that alias as kc_idp_hint when starting authentication. This keeps provider selection tied to your application's organization configuration.

In an Auth.js integration, the application must also pass the appropriate identity provider hint in the authorization request for the selected organization. The provider's alias must match the alias configured in Keycloak.

For example, if the provider's alias is microsoft-entra, Keycloak uses that connection to redirect the user directly to the customer's identity provider. This skips the default identity provider selection screen.

You can also use Keycloak Organizations to associate verified email domains with customer organizations and configure identity provider redirection based on those domains. This makes the login experience smoother for employees who enter their company email address.

Keep organization resolution on the server and validate the resulting identity before granting access to customer resources. A login URL or email domain helps route the authentication request, but your application must still enforce organization membership and permissions.

Require Multi-Factor Authentication in Keycloak

A password confirms that someone knows the account credentials, but it does not provide the additional protection required by many SaaS products and enterprise customers. Multi-factor authentication (MFA) adds another verification step, such as a time-based one-time password (TOTP) or a WebAuthn security credential.

Keycloak handles this through its authentication flows. Your Next.js application does not need to build an OTP form, generate verification codes, or manage authenticator credentials. Users complete the additional authentication step on Keycloak's login pages, and Auth.js receives the result after the full authentication flow succeeds.

Configure OTP authentication

Keycloak supports time-based one-time passwords through authenticator applications. To enable OTP registration, open the Admin Console and navigate to Authentication → Required Actions. Enable Configure OTP so users can register an authenticator application with their Keycloak account.

Next, open Authentication → Flows and review the browser authentication flow. Keycloak provides a conditional two-factor authentication subflow that supports OTP when the user has configured an OTP credential. Set the appropriate execution requirements to make OTP mandatory for the users covered by your policy.

Enabling Configure OTP makes the required action available, but it does not automatically force every user to register an authenticator. To require OTP for new users, enable its Default Action setting under Authentication → Required Actions. For existing users, assign the Configure OTP required action to their accounts or configure an authentication flow that enforces OTP enrollment. The Conditional 2FA subflow handles users who already have an OTP credential.

Support WebAuthn and passkeys

OTP is a practical MFA option, but Keycloak also supports WebAuthn. This standard allows users to authenticate with security keys and platform authenticators, including supported fingerprint readers and device-based passkeys.

To enable WebAuthn, open Authentication → Required Actions and enable Webauthn Register. Then configure the browser authentication flow to include the WebAuthn Authenticator execution. You can make WebAuthn an alternative to OTP, allowing users with registered credentials to choose their preferred second factor.

Keycloak also supports recovery authentication codes, giving users a way to regain access when their usual second factor is unavailable. These options help your team offer a more flexible MFA experience without implementing each authentication method inside Next.js.

Decide where MFA should be enforced

There is one important detail when combining MFA with enterprise SSO: the customer's external identity provider may already enforce its own MFA policies. For example, a company using Microsoft Entra ID might require employees to complete an authenticator challenge before granting access to your SaaS.

Your team needs a clear policy for this arrangement. You can rely on the customer's identity provider to enforce MFA, require an additional factor through Keycloak, or define different requirements for different customer groups.

Keep in mind that Keycloak's normal browser flow does not automatically continue with its remaining authentication steps after a successful external identity provider login. If you need Keycloak to require an additional factor after brokered authentication, configure a suitable post-login authentication flow.

This distinction prevents a common implementation mistake: enabling OTP in the local Keycloak login flow and assuming that every user signing in through an external identity provider will automatically be prompted for it.

Run Keycloak Without Managing the Infrastructure with Skycloak

The architecture described in this guide still uses Keycloak as its identity provider. The difference is who operates the infrastructure behind it.

Running Keycloak yourself means taking responsibility for hosting, database operations, updates, security patches, scaling, and availability. Those tasks matter because authentication is part of your application's critical infrastructure. If the identity service becomes unavailable, users may lose access to your product even when the Next.js application itself is running normally.

Skycloak provides managed Keycloak hosting, handling the underlying infrastructure while giving your team full Keycloak admin access. You can configure realms, clients, identity providers, authentication flows, users, and other Keycloak features through the familiar administration interface.

For the Next.js integration, the application still connects to Keycloak through its OIDC issuer URL. Your Auth.js provider configuration follows the same pattern shown earlier. You use the issuer URL and client credentials supplied for your Skycloak deployment, so the application does not need a different authentication integration.

There are a few practical details worth knowing:

  • Unlimited users: Every Skycloak plan supports unlimited users, with pricing based on infrastructure rather than monthly active users.
  • Full Keycloak administration: You retain full access to Keycloak's administration features and configuration.
  • Deployment regions: Paid plans let you choose your deployment region, while the free trial runs in the US.
  • Free trial: You can try Skycloak for 21 days without providing a credit card.

This setup lets a SaaS team keep the flexibility of Keycloak while avoiding the day-to-day work of operating its infrastructure. Your developers can focus on the Next.js application, tenant permissions, onboarding, and product features while Skycloak manages the hosting layer.

Explore Skycloak's pricing and plans to compare the available options for managed Keycloak infrastructure.

Frequently Asked Questions

How do I add Keycloak authentication to a Next.js application?
You can add Keycloak authentication to a Next.js application by configuring Keycloak as an OpenID Connect provider in Auth.js. Create a confidential client in Keycloak, configure the issuer URL and client credentials as environment var...