Skip to main content
Docs

Clerk Express SDK

The Clerk Express SDK provides a powerful set of tools and utilities to seamlessly integrate authentication, user management, and organization management into your Express application. Refer to the quickstart to get started.

Important

If you are upgrading from the Node SDK, see the upgrade guide for more information.

clerkMiddleware()

The clerkMiddleware() middleware checks the request's cookies and headers for a session JWT and if found, attaches the object to the request object under the auth key. See the reference doc for more information.

requireAuth()

The requireAuth() middleware acts similarly to clerkMiddleware(), but also protects your routes by redirecting unauthenticated users to the homepage. See the reference doc for more information.

getAuth()

The getAuth() helper retrieves authentication state from the request object. It returns the , which includes helpful authentication information like the user's ID, session ID, and organization ID. It's also useful for protecting routes. See the reference doc for more information.

clerkClient

provides access to Backend API resources and low-level authentication utilities for JavaScript environments. For example, to retrieve a list of all users in your application, you can use the users.getUserList() method from the JS Backend SDK instead of manually making a fetch request to the https://api.clerk.com/v1/users endpoint.

All resource operations are mounted as sub-APIs on the clerkClient object. See the for more information.

Example: Use clerkClient to get a user's information

The following example uses clerkClient to get information about the currently signed-in user. If the user is authenticated, their userId is passed to to get the current user's object. If not authenticated, the request is rejected with a 401 status code.

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

const app = express()
const PORT = 3000

// Apply `clerkMiddleware()` to all routes
app.use(clerkMiddleware())

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

  // If user isn't authenticated, return a 401 error
  if (!isAuthenticated) {
    return res.status(401).json({ error: 'User not authenticated' })
  }

  // Use `clerkClient` to access Clerk's JS Backend SDK methods
  // and 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(`Server is running on http://localhost:${PORT}`)
})

Feedback

What did you think of this content?

Last updated on