skip to content

In an Express 5 app, how do you mount Auth.js through @auth/express, and how does a protected route read the session?

level: middleimportance: should knowfreq 30%

answer

  1. one handler, many endpoints
  2. plain prefix, no bare star
  3. the same config object twice
  4. session or null
  5. trusted host in production

basics

~20 s

Mount ExpressAuth(config) on a plain prefix with app.use('/auth', ...) so it serves the sign-in, callback, sign-out and session endpoints, set AUTH_SECRET, and read the user with getSession(req, config), which resolves to the session or null.

solid answer

~40 s

`@auth/express` exports `ExpressAuth`, which turns an Auth.js config (providers, callbacks, an optional adapter) into one Express middleware. Mounted with `app.use('/auth', ExpressAuth(config))`, it answers `/auth/signin`, `/auth/callback/<provider>`, `/auth/signout`, `/auth/session` and `/auth/csrf` itself and runs its own JSON and urlencoded parsers. In Express 5, do not copy the package's own `'/auth/*'` example: an unnamed wildcard throws `Missing parameter name` when the route is registered, and `'/auth/*splat'` mounts but breaks how it works out its base path. To protect routes, write a middleware that awaits `getSession(req, config)` with the same config, stores the result on `res.locals.session` and returns 401 or redirects when it is `null`. It needs `AUTH_SECRET`, and in production `AUTH_URL` or `AUTH_TRUST_HOST`. The package is 0.x and documented as experimental.

code

javascript · 19 lines
javascript
import express from 'express'
import { ExpressAuth, getSession } from '@auth/express'
import GitHub from '@auth/express/providers/github'

const app = express()
const authConfig = { providers: [GitHub] }

app.use('/auth', ExpressAuth(authConfig))

async function requireSession(req, res, next) {
  const session = await getSession(req, authConfig)
  if (!session?.user) return res.status(401).json({ error: 'sign in first' })
  res.locals.session = session
  next()
}

app.get('/api/me', requireSession, (req, res) => {
  res.json({ user: res.locals.session.user })
})

go deeper

for a junior

Recall that ExpressAuth is one middleware that serves all the sign-in endpoints, and that getSession(req, config) gives you the session or null.

for a middle

Explain why the mount must be a plain prefix in Express 5, how a protection middleware uses getSession and res.locals, and which environment variables Auth.js reads.

for a senior

Diagnose the production 500 from UntrustedHost and the 400 from a wildcard mount, and keep one shared config module so session reads and the handler agree.

for a principal

Weigh building on a 0.x package documented as experimental: pin it, test each upgrade, and know what you would rewrite if its API moves.

## What @auth/express gives an Express app **Auth.js** is a sign-in library built around providers (OAuth and OpenID Connect services, email links, a `Credentials` provider for your own check) and callbacks. **`@auth/express`** is its Express integration. It exports two functions that matter here: - **`ExpressAuth(config)`** returns an `(req, res, next)` middleware that answers every Auth.js endpoint: sign-in, the provider callback, sign-out, the session read and the CSRF token. - **`getSession(req, config)`** returns a promise of the current session, or `null` when the visitor is not signed in. Unlike Passport, which authenticates a request but mounts no routes, `ExpressAuth` *is* the set of routes. You do not write a login handler or a callback handler; you configure providers and mount one middleware. It also runs `express.json()` and `express.urlencoded({ extended: true })` on its own requests, so it does not depend on whatever body parsers the rest of the app mounts. It only sees requests under its own mount path, so mounting it protects nothing by itself. ## Mounting it in Express 5 The package's own doc block shows `app.use("/auth/*", ExpressAuth(...))`. That line uses Express 4 route syntax, and in Express 5 it fails at startup, because path-to-regexp v8 requires every wildcard to have a name. | Mount path in Express 5 | What happens | |---|---| | `app.use('/auth/*', ...)` | Throws `Missing parameter name at index 7: /auth/*` when the line runs | | `app.use('/auth/*splat', ...)` | Mounts, but every Auth.js request answers 400 `Bad request.` and logs `UnknownAction` | | `app.use('/auth', ...)` | Works: `/auth/csrf`, `/auth/session`, `/auth/signin/github` all resolve | The middle row is the subtle one. `ExpressAuth` derives its base path from `req.baseUrl`, splitting it on the Express 4 positional wildcard `req.params[0]`. Express 5 names wildcards and stores them as arrays, so there is no `params[0]`; and a mount path ending in a wildcard makes `req.baseUrl` the whole matched path, action included. Auth.js then cannot find the action. A plain prefix mount sets `req.baseUrl` to `/auth`, which is exactly the base path it wants. Provider callback URLs follow the mount: with `/auth`, a GitHub provider's callback is `[origin]/auth/callback/github`. ## Reading the session in your own routes Protection is a middleware you write. A typical sequence: 1. Keep the config in one module and pass **the same object** to `ExpressAuth` and to every `getSession` call. `getSession(req)` with no config crashes with a `TypeError`, even though one example in the package's doc block omits the argument. 2. In the middleware, `await getSession(req, authConfig)`. It replays the request's cookie against the session endpoint internally and resolves to a session object (with `user` and `expires`) or to `null`. 3. On `null`, answer 401 for an API or `res.redirect('/login')` for pages; otherwise put the session on `res.locals.session` and call `next()`. 4. Apply it per route, or with `router.use()` on an `express.Router` that groups the protected routes. Because Express 5 forwards a rejected promise from an `async` middleware to error-handling middleware, a configuration error thrown by `getSession` reaches your error handler without a wrapper. ## What it reads from the environment - **`AUTH_SECRET`** is required; without it Auth.js reports `MissingSecret`. The doc block asks for a random string of at least 32 characters. - **`AUTH_<PROVIDER>_ID` and `AUTH_<PROVIDER>_SECRET`** (for example `AUTH_GITHUB_ID`) fill a provider's client credentials when the config does not. - **`AUTH_URL`** fixes the public origin; without it the origin comes from the `X-Forwarded-Host` or `Host` header. - **`AUTH_TRUST_HOST`** or the `trustHost` option: outside production the host is trusted by default, but with `NODE_ENV=production` and neither `AUTH_URL` nor `AUTH_TRUST_HOST` set, every Auth.js request fails with `UntrustedHost` and the client sees a 500 saying there was a problem with the server configuration. The doc block also recommends `app.set('trust proxy', true)` behind a proxy so the HTTPS protocol is detected; the trust-proxy setting itself is covered with production hardening. ## Where it sits in the middleware order - Mount `ExpressAuth` on its own prefix; it receives only requests under that prefix, so it neither guards nor hides your other routes. - Put your session-reading middleware on the routes or routers that need it: app level for server-rendered pages, a router for an API. - Anything mounted earlier on the same `/auth` prefix runs first and can answer before Auth.js sees the request. ## Its status `@auth/express` is still a 0.x release built on a 0.x `@auth/core`, ESM only, with a peer range of Express `^4.18.2 || ^5.0.0`. Its own documentation says it is **experimental** and that the API will change. Treat it as a pinned dependency you re-test on every upgrade, not as a stable 1.x contract.

  • Auth.js works on a laptop, but in production every /auth request returns 500. What is the likely cause?
    With `NODE_ENV=production`, Auth.js trusts the request's host only when `AUTH_URL`, `AUTH_TRUST_HOST` or `trustHost: true` says so. Otherwise it logs `UntrustedHost` and answers with a server-configuration error, and `getSession` throws the same error into your error middleware. Set `AUTH_URL` to the public origin, or trust the host when a proxy you control sets it.
  • Does ExpressAuth need express.json() mounted before it?
    No. `ExpressAuth` runs `express.json()` and `express.urlencoded({ extended: true })` itself on each request it handles, so its sign-in and sign-out POSTs are parsed either way. Your other routes still need their own parsers. Those POSTs must also carry the `csrfToken` fetched from `/auth/csrf`.

  • Copies app.use('/auth/*', ExpressAuth(config)) into an Express 5 app unchanged
  • Believes mounting ExpressAuth makes every later route require a signed-in user
  • Calls getSession(req) without passing the same config object
  • Presents @auth/express as a stable API that will not change
  • Expects Auth.js to run in production with neither AUTH_URL nor AUTH_TRUST_HOST set

Assumes Express 5, whose path-to-regexp v8 rejects the unnamed '/auth/*' wildcard the package's Express 4 era example uses.