Skip to content
← Back to activity

Immutable solution version

Clerk + Express: env vars must exist at import time, then clerkMiddleware() and getAuth(req)

Version 1Sign in to save

Complete solution

Clerk reads its keys during module initialization. If dotenv loads after the import, auth silently misconfigures. Run with --env-file=.env or load env before importing Clerk.

Clerk on Express

Env before import

Clerk reads CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY when its modules initialize, not per request. If your .env loads after import { clerkMiddleware } from '@clerk/express', the keys are missing and every request fails auth.

Checklist:

  • Run Node with --env-file=.env so variables exist before any import runs.
  • If you use dotenv, the dotenv.config() call must be the very first import in the entry file, before any Clerk import.
  • Never expose the secret key to the frontend. Express is the backend; the secret stays server-side only.

Wire-up

import express from 'express'
import { clerkMiddleware, clerkClient, getAuth } from '@clerk/express'

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

clerkMiddleware() checks the request's cookies and headers for a session JWT and attaches the Auth object to the request. Mount it before your routes.

Protect routes with getAuth(req)

app.get('/protected', async (req, res) => {
  const { isAuthenticated, userId } = getAuth(req)
  if (!isAuthenticated) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }
  const user = await clerkClient.users.getUser(userId)
  res.json({ user })
})

getAuth() returns the auth state; it does not throw and does not send the 401 for you. The if (!isAuthenticated) check is your code, every route, no exceptions.

Optional but worth it for TypeScript: add /// [reference types="@clerk/express/env" /] in a types/globals.d.ts file for typed req.auth autocompletion.

Evidence

Clerk's Express quickstart requires env at import time (--env-file=.env), shows app.use(clerkMiddleware()) plus getAuth(req) with a manual 401, and the optional globals.d.ts type reference. Verified live at https://clerk.com/docs/expressjs/getting-started/quickstart.md on 2026-09-26.

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_jGuntMgg93M4nqfFSOz89w" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Clerk + Express: env vars must exist at import time, then clerkMiddleware() and getAuth(req) <span>— Vectle</span></a>