skip to content

After adding Clerk's clerkMiddleware() to an Express API, requests with no session still reach your handlers. Why, and how should you protect routes?

level: seniorimportance: should knowfreq 25%

answer

  1. authenticates, does not authorize
  2. req.auth is attached, next() runs
  3. userId null means signed out
  4. a redirect is not a 401
  5. order: middleware before getAuth

basics

~20 s

clerkMiddleware() only reads the session token and attaches the auth state to the request; it calls next() for signed-out requests too. Protect routes with your own middleware that checks getAuth(req).userId and returns 401 when it is null.

solid answer

~40 s

`clerkMiddleware()` from `@clerk/express` checks the request's cookies and headers for a session token, verifies it with your Clerk keys, and attaches the result to the request as `req.auth`, a function, before calling `next()`. A request with no token is not rejected: its auth state simply has `userId: null`. Protection is a separate step: a middleware that calls `getAuth(req)`, returns `res.status(401)` when `userId` is null, and is applied per route or with `router.use()` on the protected `express.Router`. The older `requireAuth()` is deprecated in @clerk/express 2.1.77, and it redirects signed-out requests to `signInUrl`, `CLERK_SIGN_IN_URL` or `/`, which is the wrong answer for a JSON API. `getAuth` throws if `clerkMiddleware()` was not registered earlier in the chain.

code

javascript · 16 lines
javascript
import express from 'express'
import { clerkMiddleware, getAuth } from '@clerk/express'

const app = express()
app.use(clerkMiddleware())

function requireUser(req, res, next) {
  const { userId } = getAuth(req)
  if (!userId) return res.status(401).json({ error: 'Unauthorized' })
  next()
}

const api = express.Router()
api.use(requireUser)
api.get('/projects', (req, res) => res.json({ owner: getAuth(req).userId }))
app.use('/api', api)

go deeper

for a junior

Recall that clerkMiddleware() identifies the caller and getAuth(req).userId is null when nobody is signed in.

for a middle

Explain the protection middleware: check userId, answer 401, apply it to the protected router, and keep clerkMiddleware() mounted first.

for a senior

Diagnose open routes, the 302 from requireAuth, the getAuth ordering error and missing keys, and separate 401 from 403 with has().

for a principal

Recognise that a hosted provider makes every request depend on vendor tokens and moves user data off your systems; plan for that in reviews.

## What clerkMiddleware actually does **Clerk** is a hosted identity service: users, their credentials, their sessions and the sign-in screens live with the vendor, and your Express app only receives requests that carry a Clerk session token. The **`@clerk/express`** package (2.1.77 here) connects the two with three exports that matter: - **`clerkMiddleware(options)`** reads `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` (or the same options), looks for a session token in the request's cookies and headers, verifies it, and attaches the outcome to the request as **`req.auth`**, a branded function returning the auth object. Then it calls `next()`. - **`getAuth(req)`** returns that auth object: `userId`, session details and a `has()` helper for permission checks. - **`clerkClient`** calls the vendor's backend API for anything not in the token, such as the user's profile or a user list. The key word is *attaches*. `clerkMiddleware()` answers "who is this?", not "may they come in?". A request with no session token goes through with signed-out auth state, `userId: null`, and reaches every route after it. That lets public routes and signed-in routes share one middleware. ## Protecting routes yourself 1. Mount `app.use(clerkMiddleware())` before any route that needs auth state. 2. Write a small middleware that calls `getAuth(req)` and returns **401** with a JSON body when `userId` is `null`. 3. Apply it where it belongs: on individual routes, or with `router.use()` on an `express.Router` that groups the protected endpoints, then mount that router. 4. For finer checks, use `getAuth(req).has({ permission: '...' })` and answer **403** when the user is known but not allowed. The code example below does exactly this; a request without a token gets `401 {"error":"Unauthorized"}`. ## Why requireAuth is not the answer `@clerk/express` still exports **`requireAuth()`**, and its README still shows it. In 2.1.77 the type declarations mark it `@deprecated` ("will be removed in the next major version"), and calling it prints a deprecation warning. Its behaviour is also wrong for an API: a signed-out request is **redirected**, to the `signInUrl` option, else `CLERK_SIGN_IN_URL`, else `/`, so a JSON client gets a `302` instead of a `401`. The replacement the package recommends is the pattern above: `clerkMiddleware()` plus `getAuth()`. ## Failure modes that look like Clerk bugs | Symptom | Cause | |---|---| | Signed-out requests reach protected handlers | Only `clerkMiddleware()` is mounted; no route checks `userId` | | Every request fails with "Publishable key is missing." | `CLERK_PUBLISHABLE_KEY` not loaded before the middleware runs | | A route throws: The "clerkMiddleware" should be registered before using "getAuth" | The route or router is registered before `app.use(clerkMiddleware())` | | A JSON client receives a 302 to `/` | `requireAuth()` used on an API route without `signInUrl` | | Code reading `req.auth.userId` gets `undefined` | `req.auth` is a function in this version; use `getAuth(req)` | The thrown errors in the last rows reach Express's error-handling middleware like any other error thrown in a handler. ## Where the check belongs in the Express app Placement decides what is protected, so treat it as part of the design: - **Global `clerkMiddleware()`, scoped checks.** Mount `clerkMiddleware()` once with `app.use()` near the top, and put the `userId` check on the routers that need it. Public routes such as a health check or a webhook receiver then stay reachable. - **Webhooks are different.** A request from the vendor's webhook sender carries no user session; it is checked with `verifyWebhook(req)` from `@clerk/express/webhooks`, which verifies the signature against `CLERK_WEBHOOK_SIGNING_SECRET`, never with `getAuth`. - **Tests.** In route tests, a request with no token must get your 401, which proves the check is mounted; a test that only asserts the 200 path cannot catch an open route. ## What lives where With Clerk, the Express app holds **no user table and no session store**: no `express-session`, no adapter. Users, their credentials and their sessions are held by the vendor and read back through `clerkClient`. That is the speed you bought. The trade is that every authenticated request depends on Clerk-issued tokens and keys, and moving off it later means replacing every `getAuth` call, the client-side sign-in, and the user records themselves.

  • A route needs an organisation permission, not just a signed-in user. How do you check that with Clerk in Express?
    Call `getAuth(req).has({ permission: 'org:...' })` in a middleware after `clerkMiddleware()`. Return 401 when `userId` is null and 403 when the user is signed in but `has()` returns false, so the client can tell 'sign in' from 'not allowed'.
  • Where does a handler get the user's email address when Clerk holds the users?
    Not from your database: there is no user table. Use the `clerkClient.users` methods to fetch the user by `getAuth(req).userId` from the vendor's backend API, and cache or copy only what you need. Every such fetch is a network call to the vendor.

  • Believes clerkMiddleware() rejects requests that carry no session
  • Protects a JSON API with requireAuth() and accepts the redirect
  • Registers routes that call getAuth before app.use(clerkMiddleware())
  • Reads req.auth.userId as a property instead of calling getAuth(req)
  • Expects to query Clerk users from the application's own database