Docs

Clerk Express SDK

Clerk makes it simple to add authentication to your Express application. This documentation covers the capabilities and methods available from Clerk's Express SDK.

See the quickstart to get started.

Important

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

Available methods

clerkMiddleware()

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.

import { clerkMiddleware } from '@clerk/express'

const app = express()

// Pass no parameters
app.use(clerkMiddleware())

// Pass options
app.use(clerkMiddleware(options))

Options

The clerkMiddleware() function accepts these options plus the following:

  • Name
    clerkClient
    Type
    ClerkClient
    Description

    An instance of the ClerkClient class. This is used to interact with the Clerk API.

  • Name
    debug
    Type
    boolean
    Description

    A flag to enable debug mode. When enabled, the middleware will log debug information to the console.

  • Name
    enableHandshake
    Type
    boolean
    Description

    Enables Clerk's handshake flow, which helps verify the session state when a session JWT has expired. It issues a 307 redirect to refresh the session JWT if the user is still logged in. Defaults to true.

requireAuth()

The requireAuth() middleware functions similarly to clerkMiddleware(), but also protects your routes by redirecting unauthenticated users to the sign-in page. It will look for a CLERK_SIGN_IN_URL environment variable and use that by default. If not present, you must pass a sign in URL to the middleware as an option.

import { requireAuth } from '@clerk/express'
import express from 'express'

const app = express()

// Apply middleware to all routes
app.use(requireAuth())

// Apply middleware to a specific route - requires `process.env.CLERK_SIGN_IN_URL` to be present
app.get('/protected', requireAuth(), (req, res) => {
  res.send('This is a protected route')
})

// Use a custom sign-in URL instead of the environment variable
app.get('/protected', requireAuth({ signInUrl: '/sign-in' }), (req, res) => {
  res.send('This is a protected route')
})

This middleware accepts the same options as clerkMiddleware().

getAuth()

The getAuth() helper retrieves authentication state from the request object. See the Next.js reference documentation for more information on how to use the returned auth object.

The following example uses requireAuth() to protect the route based on authentication status, and then uses getAuth() to protect the route based on authorization status.

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

const app = express()
const port = 3000

// Apply centralized middleware
app.use(clerkMiddleware())

// Protect a route based on authorization status
const hasPermission = (req, res, next) => {
  const auth = getAuth(req)

  // Handle if the user is not authorized
  if (!auth.has({ permission: 'org:admin:testpermission' })) {
    return res.status(403).send('Forbidden')
  }

  return next()
}

app.get('/path', requireAuth(), hasPermission, (req, res) => res.json(req.auth))

// Start the server and listen on the specified port
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`)
})

clerkClient

Clerk's JavaScript Backend SDK exposes the Backend API resources and low-level authentication utilities for JavaScript environments. For example, if you wanted to get a list of all users in your application, instead of creating a fetch to the https://api.clerk.com/v1/users endpoint, you can use the users.getUserList() method provided by the JavaScript Backend SDK.

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

import { clerkClient, requireAuth } from '@clerk/express'
import express from 'express'

const app = express()
const port = 3000

app.get('/users', async (req, res) => {
  // Get the `userId` from the `Auth` object
  const userId = req.auth.userId

  if (!userId) {
    return void res.status(400).json({ error: 'Error: No signed-in user' })
  }

  // Use the userId to get information about the user
  const user = await clerkClient.users.getUser(userId)
  return void res.status(200).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