# Connecting with Node.js

This guide explains how to establish a secure connection between a Node.js application and a Keycloak identity provider using the <span class="s2">keycloak-connect</span> middleware. It walks through the necessary setup, configuration, and usage of a protected route that requires authentication.

## **Variables**

Certain parameters must be provided to integrate a Node.js application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%;"><thead><tr><th style="border-color: rgb(0, 0, 0); width: 15.8492%;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 44.4607%;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 39.6901%;">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`REALM`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">The realm name from the Keycloak Admin Console

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Defines the namespace for authentication and authorization

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`AUTH_SERVER_URL`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">The full realm URL from Keycloak (e.g., <span class="s1">https://your-domain/realms/xyz</span>)

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Used as the OIDC issuer base URL

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">Client ID from the Keycloak Clients page

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Identifies the application in Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">Secret for the OIDC client, found in the Credentials tab of the client

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Authenticates the Node.js application to Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`REDIRECT_URI`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">URI where users are redirected after authentication

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Ensures Keycloak returns control to your app after login

</td></tr></tbody></table>

These values can usually be found in the Keycloak Admin Console under <span class="s1">**Clients**</span> and <span class="s1">**Realm Settings**</span>. Make sure to copy these details and add them to the code moving ahead.

## **Prerequisites**

#### **Install Node.js and NPM**

Check if Node.js is installed by running:

```
node -v
```

If not installed, download it from [https://nodejs.org](https://nodejs.org) and install.

Verify NPM installation:

```
npm -v
```

#### **Install Required Packages**

The <span class="s2">keycloak-connect</span> package enables Node.js applications to authenticate using Keycloak. Install the required packages using:

```
npm install express express-session keycloak-connect
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">keycloak.js</span> and add the following code:

```javascript
const express = require("express");
const session = require("express-session");
const Keycloak = require("keycloak-connect");

const app = express();
const port = process.env.PORT || 3000;

const memoryStore = new session.MemoryStore();

app.use(
  session({
    secret: "supersecret",
    resave: false,
    saveUninitialized: true,
    store: memoryStore,
  })
);

const keycloakConfig = {
  realm: "REALM",
  authServerUrl: "AUTH_SERVER_URL",
  clientId: "CLIENT_ID",
  credentials: {
    secret: "CLIENT_SECRET",
  },
  sslRequired: "external",
  confidentialPort: 0,
};

const keycloak = new Keycloak({ store: memoryStore }, keycloakConfig);
app.use(keycloak.middleware());

app.get("/", (req, res) => {
  res.send("Welcome to the public route.");
});

app.get("/protected", keycloak.protect(), (req, res) => {
  res.send("You have accessed a protected route.");
});

app.get("/logout", (req, res) => {
  req.logout();
  res.redirect("/");
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
```

Replace the placeholder values (<span class="s1">REALM</span>, <span class="s1">AUTH\_SERVER\_URL</span>, <span class="s1">CLIENT\_ID</span>, and <span class="s1">CLIENT\_SECRET</span>) with actual values from your Keycloak server.

## **Execution**

Open the terminal or command prompt and navigate to the directory where <span class="s1">keycloak.js</span> is saved. Once in the correct directory, run the script with the command:

```
node keycloak.js
```

If the connection is successful:

1. Visit <span class="s1">http://localhost:3000</span> in your browser to access the public route.
2. Visit <span class="s1">http://localhost:3000/protected</span> to trigger Keycloak authentication.
3. Upon successful login, you’ll be redirected back and see protected content.
4. Visit <span class="s1">http://localhost:3000/logout</span> to log out and end the session.