Skip to main content

Express Quickstart

Learn how to integrate Clerk into your Express backend for secure user authentication and management. This guide focuses on backend implementation and requires a Clerk frontend SDK to function correctly.

Create a new Express app

If you don't already have an Express app, run the following commands to create a new one.

mkdir clerk-express
cd clerk-express
npm init -y
npm install express
mkdir clerk-express
cd clerk-express
pnpm init -y
pnpm add express
mkdir clerk-express
cd clerk-express
yarn init -y
yarn add express
mkdir clerk-express
cd clerk-express
bun init -y
bun add express

Install @clerk/express

The Clerk Express SDK provides a range of backend utilities to simplify user authentication and management in your application.

Run the following command to install the SDK:

npm install @clerk/express
pnpm add @clerk/express
yarn add @clerk/express
bun add @clerk/express
.env
CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY
CLERK_SECRET_KEY=YOUR_SECRET_KEY

Node can load .env files natively. When running your app, use the --env-file=.env flag so environment variables can be accessed at import time.

Add clerkMiddleware() to your app

The clerkMiddleware() function checks the request's cookies and headers for a session JWT and, if found, attaches the Auth object to the request object under the auth key.

index.ts
import express from 'express'
import { clerkMiddleware } from '@clerk/express'

const app = express()
const PORT = 3000

app.use(clerkMiddleware())

// Start the server and listen on the specified port
app.listen(PORT, () => {
  console.log(`Example app listening at http://localhost:${PORT}`)
})

Protect your routes using getAuth()

To protect your routes, use the getAuth() helper in the route body. getAuth() returns the request's auth state, so you can choose how your application responds when the user isn't authenticated.

In the following example, getAuth() is used to protect the /protected route. If the user isn't authenticated, the route returns a 401 status code. If the user is authenticated, the userId is passed to clerkClient.users.getUser() to fetch the current user's User object.

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

const app = express()
const PORT = 3000

app.use(clerkMiddleware())

app.get('/protected', async (req, res) => {
  // Use `getAuth()` to get the user's `userId`
  const { isAuthenticated, userId } = getAuth(req)

  if (!isAuthenticated) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }

  // Use the `getUser()` method to get the user's User object
  const user = await clerkClient.users.getUser(userId)

  res.json({ user })
})

// Start the server and listen on the specified port
app.listen(PORT, () => {
  console.log(`Example app listening at http://localhost:${PORT}`)
})

Add global TypeScript type (optional)

If you're using TypeScript, add a global type reference to your project to enable auto-completion and type checking for the auth object in Express request handlers.

  1. In your application's root folder, create a types/ directory.
  2. Inside this directory, create a globals.d.ts file with the following code.
types/globals.d.ts
/// <reference types="@clerk/express/env" />

Next steps

Explore the most relevant next steps for your backend SDK using the following guides.

Protect routes using getAuth()

Learn how to protect specific routes from unauthenticated users.

Protect routes based on authorization status

Learn how to protect a route based on both authentication and authorization status.

Deploy to production

Learn how to deploy your Clerk app to production.

Clerk Express SDK reference

Learn about the Clerk Express SDK and how to integrate it into your app.

More to explore

Explore additional Clerk features that help you build, manage, and grow your application.

  • Organizations - Organizations are shared accounts that let teams collaborate, manage members and roles, and control access to shared resources.
  • Billing - Billing enables you to manage subscriptions, free trials, payments, plans, and billing-related webhook events for B2C and B2B applications.
  • Waitlist - Waitlist lets you collect signups and control access to new products or features before launch through a simple, integrated workflow.

Feedback

What did you think of this content?

Last updated on