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.
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))clerkMiddleware() options
The clerkMiddleware() function accepts an optional object. The following options are available:
- Name
 audience?- Type
 string | string[]- Description
 A string or list of audiences. If passed, it is checked against the
audclaim in the token.
- Name
 authorizedParties?- Type
 string[]- Description
 An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack. For example:
['http://localhost:3000', 'https://example.com']
- Name
 clockSkewInMs?- Type
 number- Description
 Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. Defaults to 5000 ms (5 seconds).
- Name
 domain?- Type
 string- Description
 The domain used for satellites to inform Clerk where this application is deployed.
- Name
 isSatellite?- Type
 boolean- Description
 When using Clerk's satellite feature, this should be set to
truefor secondary domains.
- Name
 jwtKey- Type
 string- Description
 Used to verify the session token in a networkless manner. Supply the JWKS Public Key from the API keys page in the Clerk Dashboard. It's recommended to use the environment variable instead. For more information, refer to Manual JWT verification.
- Name
 organizationSyncOptions?- Type
 OrganizationSyncOptions | undefined- Description
 Used to activate a specific organization or personal account based on URL path parameters. If there's a mismatch between the active organization in the session (e.g., as reported by
auth()) and the organization indicated by the URL, the middleware will attempt to activate the organization specified in the URL.
- Name
 proxyUrl?- Type
 string- Description
 Specify the URL of the proxy, if using a proxy.
- Name
 signInUrl- Type
 string- Description
 The full URL or path to your sign-in page. Needs to point to your primary application on the client-side. Required for a satellite application in a development instance. It's recommended to use the environment variable instead.
- Name
 signUpUrl- Type
 string- Description
 The full URL or path to your sign-up page. Needs to point to your primary application on the client-side. Required for a satellite application in a development instance. It's recommended to use the environment variable instead.
- Name
 publishableKey- Type
 string- Description
 The Clerk Publishable Key for your instance. This can be found on the API keys page in the Clerk Dashboard.
- Name
 secretKey?- Type
 string- Description
 The Clerk Secret Key for your instance. This can be found on the API keys page in the Clerk Dashboard. The
CLERK_ENCRYPTION_KEYenvironment variable must be set when providingsecretKeyas an option, refer to Dynamic keys.
- Name
 clerkClient- Type
 - ClerkClient
 - Description
 An instance of the
ClerkClientclass. This is used to interact with the Clerk API.
- Name
 debug- Type
 boolean- Description
 A flag to enable debug mode. When set to
true, the middleware will log debug information to the console. Defaults tofalse.
- Name
 enableHandshake- Type
 boolean- Description
 A flag to enable Clerk's handshake flow, which helps verify the session state when a session JWT has expired. It issues a
307redirect to refresh the session JWT if the user is still logged in. Defaults totrue.
The requireAuth() middleware functions similarly to clerkMiddleware(), but also protects your routes by redirecting unauthenticated users to the homepage. It accepts the same options as clerkMiddleware().
You can also specify a custom sign-in URL to redirect unauthenticated users to by setting the CLERK_SIGN_IN_URL environment variable or by passing a signInUrl option to the middleware. It's recommended to set the environment variable.
import { requireAuth } from '@clerk/express'
import express from 'express'
const app = express()
const PORT = 3000
// Apply middleware to all routes
app.use(requireAuth())
// Apply middleware to a specific route
// Redirects to the homepage if the user is not authenticated
app.get('/protected', requireAuth(), (req, res) => {
  res.send('This is a protected route.')
})
// Redirects to a custom URL if the user is not authenticated
// Requires `CLERK_SIGN_IN_URL` to be set in env vars
app.get('/protected', requireAuth({ signInUrl: process.env.CLERK_SIGN_IN_URL }), (req, res) => {
  res.send('This is a protected route.')
})
// Redirects to a custom URL if the user is not authenticated
// Uses the `signInUrl` option instead of the environment variable
app.get('/protected', requireAuth({ signInUrl: '/sign-in' }), (req, res) => {
  res.send('This is a protected route.')
})
// Start the server and listen on the specified port
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`)
})getAuth()
The getAuth() helper retrieves authentication state from the request object. See the Next.js reference documentation for more examples on how to use the returned auth object.
getAuth() options
- Name
 acceptsToken?- Type
 TokenType- Description
 The type of authentication token(s) to accept. Valid values are:
'session_token'- authenticates a user session.'oauth_token'- authenticates a machine request using OAuth.'machine_token'- authenticates a machine request.'api_key'- authenticates a machine request using API keys.
Can be set to:
- A single token type.
 - An array of token types.
 'any'to accept all available token types.
Defaults to
'session_token'.
Example: Protecting a route with requireAuth() and role-based authorization using getAuth()
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 `clerkMiddleware()` to all routes
app.use(clerkMiddleware())
// Use `getAuth()` to 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:example' })) {
    return res.status(403).send('Forbidden')
  }
  return next()
}
// Use `requireAuth()` to protect this route
// If user is not authenticated, requireAuth() will redirect back to the homepage
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}`)
})Example: Protecting a route by accepting and verifying multiple token types using getAuth()
The following example uses getAuth() to protect the route based on token type:
- It accepts any token type 
(acceptsToken: 'any')from the request. - If the token is a 
session_token, it logs that the request is from a user session. - Otherwise, it logs that the request uses a machine token and specifies its type.
 
import express from 'express'
import { getAuth } from '@clerk/express'
const app = express()
app.get('/path', (req, res) => {
  // Use `getAuth()` to protect a route based on token type
  const authObject = getAuth(req, { acceptsToken: 'any' })
  if (authObject.tokenType === 'session_token') {
    console.log('this is session token from a user')
  } else {
    console.log('this is some other type of machine token')
    console.log('more specifically, a ' + authObject.tokenType)
  }
})clerkClient
Clerk's JavaScript Backend SDK 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 JavaScript 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 reference documentation 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 clerkClient.users.getUser() to get the current user's User object. If not authenticated, the request is rejected with a 401 status code.
import { clerkClient, requireAuth } from '@clerk/express'
import express from 'express'
const app = express()
const PORT = 3000
app.get('/user', async (req, res) => {
  // Get the `userId` from the `Auth` object
  const userId = req.auth.userId
  // If user isn't authenticated, return a 401 error
  if (!userId) {
    res.status(401).json({ error: 'User not authenticated' })
  }
  // Use `clerkClient` to access Clerk's 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
Last updated on