RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to a Next.js app

Add Keycloak login to a Next.js App Router app with Auth.js, protect a route handler with jose, and log out of Keycloak too.

Auth.js signs users in on the Next.js server with the authorization code flow, so the client is confidential and has a secret. A route handler then accepts access tokens from other callers and checks them with jose.

Written against next-auth 5.0.0-beta.32, Next.js 16.4, jose 6.2 and Keycloak 26.8, checked on 25 November 2026. next-auth 5 is still published under the beta tag; npm install next-auth without a tag installs version 4, which has a different API.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

Create the client in Keycloak

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDnextjs-app
Client authenticationOn
Authentication flowStandard flow. Turn Direct access grants off.
Root URLhttp://localhost:3000
Valid redirect URIshttp://localhost:3000/api/auth/callback/keycloak
Valid post logout redirect URIshttp://localhost:3000/
Web originsLeave empty. The browser never calls Keycloak from JavaScript.

Choose Save, then copy the secret from the Credentials tab.

For production, add your app's real URLs next to the local ones, for example https://app.example.com/api/auth/callback/keycloak and https://app.example.com/. Keycloak compares redirect URIs exactly.

Environment variables

.env.local
AUTH_SECRET=        # generate with: npx auth secret
AUTH_KEYCLOAK_ID=nextjs-app
AUTH_KEYCLOAK_SECRET=paste-the-client-secret
AUTH_KEYCLOAK_ISSUER=https://auth.example.com/realms/acme
APP_URL=http://localhost:3000
API_AUDIENCE=orders-api

AUTH_KEYCLOAK_ID, AUTH_KEYCLOAK_SECRET and AUTH_KEYCLOAK_ISSUER are the names the Keycloak provider reads on its own. The issuer must include /realms/acme and has no trailing slash. APP_URL and API_AUDIENCE are used only by the code below.

In production behind a reverse proxy, also set AUTH_TRUST_HOST=true, as the Auth.js deployment guide describes.

Install

npm install next-auth@beta jose

Add login

auth.ts
import NextAuth from "next-auth"
import Keycloak from "next-auth/providers/keycloak"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [Keycloak],
  callbacks: {
    jwt({ token, account }) {
      // On sign-in, keep the ID token for logout. It stays in the
      // encrypted session cookie; the session callback does not expose it.
      if (account?.id_token) token.idToken = account.id_token
      return token
    },
  },
})
types/next-auth.d.ts
import "next-auth/jwt"

declare module "next-auth/jwt" {
  interface JWT {
    idToken?: string
  }
}
app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth"

export const { GET, POST } = handlers

The page below reads the session with auth(). Use the same check in any server component, route handler or server action that needs a signed-in user.

app/page.tsx
import { auth } from "@/auth"
import { login, logout } from "./actions"

export default async function Home() {
  const session = await auth()

  if (!session?.user) {
    return (
      <form action={login}>
        <button type="submit">Log in</button>
      </form>
    )
  }

  return (
    <main>
      <p>Signed in as {session.user.name ?? session.user.email}</p>
      <form action={logout}>
        <button type="submit">Log out</button>
      </form>
    </main>
  )
}

login and logout are server actions in app/actions.ts, shown in Log out. Run npm run dev, open http://localhost:3000 and sign in with a user of your realm.

Protect an API

A route handler that other clients call with Authorization: Bearer <access token> must check the token's signature, issuer and audience.

Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to the client whose tokens call the API (for example your SPA's client):

  1. Open Clients, choose that client, and open its Client scopes tab.
  2. Choose <client-id>-dedicated.
  3. Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
  4. Enter a Name, set Included Custom Audience to orders-api, keep Add to access token on, and choose Save.

If your API is registered as a client in the realm, pick it under Included Client Audience instead and use its client ID as API_AUDIENCE.

lib/verify-token.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose"

const issuer = process.env.AUTH_KEYCLOAK_ISSUER!
const audience = process.env.API_AUDIENCE

// The realm's public signing keys. jose caches them and fetches
// them again when a token arrives with a key ID it has not seen.
const jwks = createRemoteJWKSet(new URL(`${issuer}/protocol/openid-connect/certs`))

export async function verifyBearerToken(request: Request): Promise<JWTPayload | null> {
  // jose skips the audience check when audience is undefined, so fail loudly.
  if (!audience) throw new Error("API_AUDIENCE is not set")

  const header = request.headers.get("authorization")
  if (!header?.startsWith("Bearer ")) return null

  try {
    const { payload } = await jwtVerify(header.slice("Bearer ".length), jwks, {
      issuer,
      audience,
    })
    return payload
  } catch {
    return null
  }
}
app/api/me/route.ts
import { verifyBearerToken } from "@/lib/verify-token"

export async function GET(request: Request) {
  const payload = await verifyBearerToken(request)
  if (!payload) {
    return Response.json(
      { error: "invalid_token" },
      { status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' } },
    )
  }
  return Response.json({ sub: payload.sub, scope: payload.scope })
}

The same verifyBearerToken works in an API outside Next.js, as long as it runs where fetch and Web Crypto are available. Paste a token into the JWT decoder to see its iss and aud, or check it against your realm's keys with the JWT verifier.

Log out

signOut() from Auth.js only clears the app's session cookie. The user is still signed in to Keycloak, so the next login goes straight through without a password. To end the Keycloak session as well, clear the cookie and then send the browser to the realm's end-session endpoint with the ID token as id_token_hint:

app/actions.ts
"use server"

import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { getToken } from "next-auth/jwt"
import { signIn, signOut } from "@/auth"

export async function login() {
  await signIn("keycloak", { redirectTo: "/" })
}

export async function logout() {
  // Read the ID token before the session cookie is cleared.
  const token = await getToken({
    req: { headers: await headers() },
    secret: process.env.AUTH_SECRET,
    // Auth.js uses the __Secure- cookie name when the app runs on https.
    secureCookie: process.env.NODE_ENV === "production",
  })

  // Clear the Auth.js session cookie without redirecting yet.
  await signOut({ redirect: false })

  // Then end the Keycloak session. Auth.js only redirects to its own
  // origin, so send the browser to the end-session endpoint ourselves.
  const url = new URL(`${process.env.AUTH_KEYCLOAK_ISSUER}/protocol/openid-connect/logout`)
  url.searchParams.set("post_logout_redirect_uri", `${process.env.APP_URL}/`)
  if (token?.idToken) {
    url.searchParams.set("id_token_hint", token.idToken)
  } else {
    url.searchParams.set("client_id", process.env.AUTH_KEYCLOAK_ID!)
  }
  redirect(url.toString())
}

post_logout_redirect_uri must be listed in Valid post logout redirect URIs. secureCookie follows NODE_ENV here on the assumption that production runs on https and development on http; set it to match your setup. The logout URL builder shows the URL this code builds.

This logout runs through the browser, so it needs nothing from us. If you also set a Backchannel logout URL on the client, Keycloak calls your app from your tenant, and outgoing connections from your tenant are closed by default. Tell us the host and port first through How to reach us and we open the connection.

Common errors

ErrorCauseFix
Keycloak shows Invalid parameter: redirect_uriThe callback URL is not in Valid redirect URIs, or differs in scheme, port or path.Add http://localhost:3000/api/auth/callback/keycloak exactly. Compare both with the redirect URI matcher.
Auth.js logs MissingSecretAUTH_SECRET is not set.Run npx auth secret and restart the dev server.
Auth.js logs UntrustedHost in productionAuth.js does not trust the host header behind your proxy.Set AUTH_TRUST_HOST=true.
Sign-in fails with unauthorized_client in the server logThe client secret is wrong, or Client authentication is off.Copy the secret again from the Credentials tab.
Keycloak shows Invalid redirect uri after Log outpost_logout_redirect_uri is not in Valid post logout redirect URIs.Add http://localhost:3000/, with the trailing slash the code sends.
Keycloak asks "Do you want to log out?"No ID token was found, so the request carried client_id instead of id_token_hint.Check the jwt callback stores idToken, and that secureCookie matches your scheme.
API returns 401, jose says unexpected "aud" claim valueThe access token has no orders-api audience.Add the Audience mapper above and get a new token.
API returns 401, jose says unexpected "iss" claim valueThe token comes from a different hostname or realm than AUTH_KEYCLOAK_ISSUER.Use the exact issuer from the realm's discovery document, see the OIDC discovery viewer.

For other OAuth error codes, see the OAuth error lookup.

FAQ

Why a confidential client and not a public one?

Auth.js exchanges the authorization code on the Next.js server, where a secret stays private. Auth.js also uses PKCE by default, so a stolen code is useless without the verifier only the server holds.

Do I need proxy.ts?

No. The Auth.js installation guide lists export { auth as proxy } from "@/auth" as an optional step that keeps the session alive on each request. Since Next.js 16 the file is proxy.ts; before that it was middleware.ts. Check the session with auth() in each page or server action either way, as Next.js recommends.

Can the Next.js server call my API with the user's access token?

Yes. Store account.access_token in the jwt callback the same way as idToken. Keycloak access tokens expire after the realm's Access Token Lifespan (5 minutes by default), so you also need to refresh them; the Auth.js refresh token rotation guide shows how.

Why does the API reject the ID token?

The ID token's aud is the client ID nextjs-app, not orders-api, so the audience check fails. That is intended: APIs take access tokens.

Sources

On this page