Keycloak Node.js Connect Adapter

26.1.1 · deprecated · verified Wed Apr 22

The `keycloak-connect` package provides a Node.js Connect-friendly middleware for integrating applications with Keycloak, an open-source identity and access management solution. It simplifies implementing authentication and authorization using Keycloak for modern applications and services. The current stable version is 26.1.1. However, this package is officially deprecated by the Keycloak project, with plans for removal in the future, and users are advised to seek alternative integration strategies. Key differentiators included its direct integration with the Connect/Express ecosystem, providing session management and protection for routes, but its deprecation signals a shift away from this specific adapter approach in favor of more generic OIDC client libraries. While it offered a streamlined setup for Keycloak, its maintenance and future are uncertain due to the deprecation notice.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `keycloak-connect` with an Express application, showing how to protect routes, configure session management, and handle basic authentication flows with a Keycloak server. It uses environment variables for sensitive Keycloak configuration.

import express from 'express';
import session from 'express-session';
import Keycloak from 'keycloak-connect';
import path from 'path';

const app = express();

// Session store setup for Keycloak
const memoryStore = new session.MemoryStore();

app.use(session({
  secret: process.env.SESSION_SECRET ?? 'superSecretSessionKey',
  resave: false,
  saveUninitialized: true,
  store: memoryStore
}));

// Keycloak configuration (replace with your actual Keycloak client details)
// This example assumes a keycloak.json file is not used and config is inline.
const keycloakConfig = {
  realm: process.env.KEYCLOAK_REALM ?? 'myrealm',
  'auth-server-url': process.env.KEYCLOAK_AUTH_SERVER_URL ?? 'http://localhost:8080/auth',
  resource: process.env.KEYCLOAK_CLIENT_ID ?? 'my-express-app',
  'public-client': true,
  'ssl-required': 'external',
  'confidential-port': 0
};

const keycloak = new Keycloak({ store: memoryStore }, keycloakConfig);

// Mount Keycloak middleware
app.use(keycloak.middleware({
  logout: '/logout',
  admin: '/admin',
  protected: '/protected'
}));

// Define routes
app.get('/', (req, res) => {
  res.send('<h1>Public Page</h1><p><a href="/protected">Go to Protected Page</a></p><p><a href="/logout">Logout</a></p>');
});

app.get('/protected', keycloak.protect(), (req, res) => {
  res.send(`<h1>Protected Page</h1><p>Welcome, ${req.kauth.grant.access_token.content.preferred_username ?? 'user'}!</p><p><a href="/">Go to Public Page</a></p><p><a href="/logout">Logout</a></p>`);
});

app.get('/login', keycloak.protect(), (req, res) => {
  res.send('You should be redirected to Keycloak for login, then back here if successful.');
});

// Error handling for Keycloak
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  if (err && err.name === 'UnauthorizedError') {
    return res.status(401).send('Unauthorized');
  }
  next(err);
});

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Ensure Keycloak is running and configured with a client named \'my-express-app\'.');
});

view raw JSON →