# Node / Express backend

Add sign-in to a Node.js Express app using the openid-client library and the Authorization Code flow with PKCE.

This guide adds OIDC sign-in to an Express app using the [`openid-client`](https://www.npmjs.com/package/openid-client) library, which handles discovery, PKCE, and token validation for you. It assumes a **confidential** client (a backend that can keep a secret).

If you have not yet registered an application, see [Before you start](https://dts-identity.com/docs/quickstarts.md#before-you-start). For the protocol behind this, see [OpenID Connect (Authorization Code + PKCE)](https://dts-identity.com/docs/quickstarts/oidc-authorization-code.md).

## 1. Install dependencies

```bash
npm install express express-session openid-client
```

## 2. Configure the client

```js
import * as client from 'openid-client';

// Your instance's login domain (issuer). openid-client reads the
// discovery document at <issuer>/.well-known/openid-configuration.
const server = new URL('https://<your-domain>');
const clientId = process.env.OIDC_CLIENT_ID;
const clientSecret = process.env.OIDC_CLIENT_SECRET;
const redirectUri = 'https://app.example.com/callback';
const scope = 'openid profile email offline_access';

// Discover endpoints and prepare the client (default: client_secret_basic).
const config = await client.discovery(server, clientId, clientSecret);
```

Keep `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` in the environment, never in source control.

## 3. Start sign-in

Build the authorization URL with a PKCE challenge and a `state`, remember both in the session, and redirect the browser.

```js
import express from 'express';
import session from 'express-session';

const app = express();
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));

app.get('/login', async (req, res) => {
  const codeVerifier = client.randomPKCECodeVerifier();
  const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
  const state = client.randomState();

  // stash for the callback
  req.session.codeVerifier = codeVerifier;
  req.session.state = state;

  const authUrl = client.buildAuthorizationUrl(config, {
    redirect_uri: redirectUri,
    scope,
    code_challenge: codeChallenge,
    code_challenge_method: 'S256',
    state,
  });

  res.redirect(authUrl.href);
});
```

## 4. Handle the callback

Exchange the code for tokens. `openid-client` validates the response, the `state`, and the PKCE verifier for you.

```js
app.get('/callback', async (req, res) => {
  const currentUrl = new URL(req.originalUrl, 'https://app.example.com');

  const tokens = await client.authorizationCodeGrant(config, currentUrl, {
    pkceCodeVerifier: req.session.codeVerifier,
    expectedState: req.session.state,
  });

  const claims = tokens.claims(); // validated ID-token claims
  req.session.user = { sub: claims.sub, name: claims.name, email: claims.email };
  req.session.idToken = tokens.id_token;

  // Optional: fetch additional claims from UserInfo
  // const userinfo = await client.fetchUserInfo(config, tokens.access_token, claims.sub);

  res.redirect('/');
});
```

## 5. Log out

Send the user to the end-session endpoint, then clear your own session.

```js
app.get('/logout', (req, res) => {
  const endSession = client.buildEndSessionUrl(config, {
    id_token_hint: req.session.idToken,
    post_logout_redirect_uri: 'https://app.example.com/',
  });
  req.session.destroy(() => res.redirect(endSession.href));
});
```

Register `https://app.example.com/` as a post-logout redirect URI on the application, the same way you register a redirect URI.

## Troubleshooting

- **The discovery call fails.** Confirm `https://<your-domain>/.well-known/openid-configuration` is reachable from your server and that the domain is your instance's login host.
- **`state` or PKCE errors on callback.** The session that started the login must be the one that handles the callback. Make sure session cookies survive the redirect (correct `SameSite` and, in production, `secure` cookies over HTTPS).
- **A refresh token is never returned.** Include `offline_access` in the scope and confirm the application is configured to receive refresh tokens.

## Next

- [React single-page app](https://dts-identity.com/docs/quickstarts/react-spa.md) for a browser-only client.
- [Applications](https://dts-identity.com/docs/integrations/applications.md) to review token lifetimes and other client settings.
