RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to a Node.js Express app

Sign users in to an Express app with Keycloak using openid-client v6 and sessions, protect API routes with jose, and log out of Keycloak.

The Express server signs users in with the authorization code flow and PKCE through openid-client, keeps the result in a server-side session, and checks bearer tokens on its API routes with jose. The server holds a client secret, so the client is confidential.

Written against openid-client 6.9, jose 6.2, Express 5.3, express-session 1.19, Node.js 22 and Keycloak 26.8, checked on 25 November 2026. openid-client 6 has a new functional API (discovery, buildAuthorizationUrl, authorizationCodeGrant); code written for version 5 (Issuer, Client) does not work with it.

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 IDexpress-app
Client authenticationOn
Authentication flowStandard flow. Turn Direct access grants off.
Root URLhttp://localhost:3000
Valid redirect URIshttp://localhost:3000/callback
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/callback and https://app.example.com/. Keycloak compares redirect URIs exactly.

Environment variables

.env
KEYCLOAK_ISSUER=https://auth.example.com/realms/acme
KEYCLOAK_CLIENT_ID=express-app
KEYCLOAK_CLIENT_SECRET=paste-the-client-secret
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string
API_AUDIENCE=orders-api

Install

npm install express express-session openid-client jose
npm install -D typescript tsx @types/express @types/express-session @types/node
npm pkg set type=module

openid-client and jose are ES modules, and the code below uses top-level await, so the project is "type": "module".

Add login

src/oidc.ts
import * as client from "openid-client"

// Downloads https://auth.example.com/realms/acme/.well-known/openid-configuration
export const config = await client.discovery(
  new URL(process.env.KEYCLOAK_ISSUER!),
  process.env.KEYCLOAK_CLIENT_ID!,
  process.env.KEYCLOAK_CLIENT_SECRET!,
)

export const appUrl = process.env.APP_URL!
export const redirectUri = `${appUrl}/callback`
src/server.ts
import express from "express"
import session from "express-session"
import * as client from "openid-client"
import { config, appUrl, redirectUri } from "./oidc.js"
import { apiRouter } from "./api.js"

declare module "express-session" {
  interface SessionData {
    state?: string
    codeVerifier?: string
    idToken?: string
    user?: { sub: string; name?: string }
  }
}

const app = express()

app.use(
  session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
    },
  }),
)

app.get("/", (req, res) => {
  if (!req.session.user) {
    res.send('<a href="/login">Log in</a>')
    return
  }
  res.send(
    `<p>Signed in as ${escapeHtml(req.session.user.name ?? req.session.user.sub)}</p>
     <form method="post" action="/logout"><button>Log out</button></form>`,
  )
})

app.get("/login", async (req, res) => {
  const codeVerifier = client.randomPKCECodeVerifier()
  const state = client.randomState()
  req.session.codeVerifier = codeVerifier
  req.session.state = state

  const url = client.buildAuthorizationUrl(config, {
    redirect_uri: redirectUri,
    scope: "openid profile email",
    code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
    code_challenge_method: "S256",
    state,
  })
  res.redirect(url.href)
})

app.get("/callback", async (req, res) => {
  const { codeVerifier, state } = req.session
  if (!codeVerifier || !state) {
    // The session cookie set by /login did not come back.
    res.status(400).send('Login expired. <a href="/login">Try again</a>')
    return
  }

  // Checks state, exchanges the code (with the client secret and PKCE
  // verifier) and validates the ID token.
  const tokens = await client.authorizationCodeGrant(
    config,
    new URL(req.originalUrl, appUrl),
    { pkceCodeVerifier: codeVerifier, expectedState: state },
  )
  const claims = tokens.claims()!

  // New session ID after login, to prevent session fixation.
  await new Promise<void>((resolve, reject) =>
    req.session.regenerate((err) => (err ? reject(err) : resolve())),
  )
  req.session.user = {
    sub: claims.sub,
    name: typeof claims.name === "string" ? claims.name : undefined,
  }
  req.session.idToken = tokens.id_token
  res.redirect("/")
})

app.post("/logout", (req, res, next) => {
  const idToken = req.session.idToken
  req.session.destroy((err) => {
    if (err) return next(err)
    // client_id is added automatically.
    const url = client.buildEndSessionUrl(config, {
      post_logout_redirect_uri: `${appUrl}/`,
      ...(idToken ? { id_token_hint: idToken } : {}),
    })
    res.redirect(url.href)
  })
})

app.use("/api", apiRouter)

app.listen(3000, () => console.log(`Listening on ${appUrl}`))

function escapeHtml(value: string) {
  return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
}

Express 5 passes errors thrown in async handlers to its error handler, so a failed code exchange returns a 500 instead of crashing the process. Start the app and sign in at http://localhost:3000:

npx tsx --env-file=.env src/server.ts

Protect an API

Routes under /api accept Authorization: Bearer <access token> from other clients, such as a single-page app, and 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:

  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.

src/api.ts
import { Router, type Request, type Response, type NextFunction } from "express"
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose"

const issuer = process.env.KEYCLOAK_ISSUER!
const audience = process.env.API_AUDIENCE
// jose skips the audience check when audience is undefined, so fail loudly.
if (!audience) throw new Error("API_AUDIENCE is not set")
const jwks = createRemoteJWKSet(new URL(`${issuer}/protocol/openid-connect/certs`))

declare global {
  namespace Express {
    interface Request {
      token?: JWTPayload
    }
  }
}

export async function requireBearer(req: Request, res: Response, next: NextFunction) {
  const header = req.get("authorization")
  if (!header?.startsWith("Bearer ")) {
    res.status(401).set("WWW-Authenticate", "Bearer").json({ error: "missing_token" })
    return
  }
  try {
    const { payload } = await jwtVerify(header.slice("Bearer ".length), jwks, {
      issuer,
      audience,
    })
    req.token = payload
    next()
  } catch {
    res
      .status(401)
      .set("WWW-Authenticate", 'Bearer error="invalid_token"')
      .json({ error: "invalid_token" })
  }
}

export const apiRouter = Router()

apiRouter.get("/me", requireBearer, (req, res) => {
  res.json({ sub: req.token?.sub, scope: req.token?.scope })
})

createRemoteJWKSet caches the realm's keys and fetches them again when a token arrives with a key ID it has not seen, so a key rotation in Keycloak needs no restart. Paste a token into the JWT decoder to see its iss and aud, or check it with the JWT verifier.

Log out

The /logout route in src/server.ts destroys the Express session, then sends the browser to the realm's end-session endpoint with buildEndSessionUrl. The URL carries id_token_hint, post_logout_redirect_uri and client_id, so Keycloak ends its own session without asking and sends the user back to http://localhost:3000/. That address must be listed in Valid post logout redirect URIs. The logout URL builder shows the same URL.

The route is a POST from a form, so another site cannot log your users out with a link or an image tag.

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_urihttp://localhost:3000/callback is not in Valid redirect URIs, or differs in scheme, port or path.Add it exactly. Compare both with the redirect URI matcher.
TypeError: fetch failed at startupdiscovery cannot reach the issuer: a typo in the hostname or realm.Open KEYCLOAK_ISSUER plus /.well-known/openid-configuration in a browser, or use the OIDC discovery viewer.
only requests to HTTPS are allowedThe issuer URL starts with http://.Use your tenant's https:// hostname.
Login expired right after signing in at KeycloakThe session cookie from /login did not come back, for example because secure is on over plain http, or the app runs behind a proxy without trust proxy.See the FAQ below on proxies.
unexpected "state" response parameter valueThe callback belongs to an older login attempt, for example from a second tab.Start again at /login.
Token exchange fails with unauthorized_clientThe 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.
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.

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

FAQ

Can I keep the default session store in production?

No. express-session's README says its default MemoryStore is not designed for production: it leaks memory and does not scale past one process. Pick one of the stores its README lists, such as one backed by Redis or PostgreSQL.

What changes behind a reverse proxy?

With secure: true cookies behind a proxy that ends TLS, Express must trust the proxy, or express-session does not set the cookie. Add app.set("trust proxy", 1) before the session middleware and set NODE_ENV=production.

Why PKCE when the client already has a secret?

PKCE binds the authorization code to the session that started the login, so a code that leaks from a log or a browser history cannot be redeemed elsewhere. Current OAuth security guidance recommends it for every client.

Does the session hold an access token?

No. This example keeps only the user and the ID token, which is all logout needs. If the server must call another API as the user, store tokens.access_token and tokens.refresh_token in the session and renew with client.refreshTokenGrant before the access token expires.

Sources

On this page