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.
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'constapp=express()// Pass no parametersapp.use(clerkMiddleware())// Pass optionsapp.use(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 aud claim 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 true for 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.
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_KEY environment variable must be set when providing secretKey as an option, refer to Dynamic keys.
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 set to true, the middleware will log debug information to the console. Defaults to false.
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 307 redirect to refresh the session JWT if the user is still logged in. Defaults to true.
The requireAuth() helper redirects unauthenticated users to the sign-in page so it should only be used for full-stack Express apps. If your client and server run on different origins, see the cross-origin requests guide.
Do not use requireAuth() for API routes. For backend API calls, use clerkMiddleware() along with getAuth() to verify sessions and return standard HTTP status codes.
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'constapp=express()constPORT=3000// Apply middleware to all routesapp.use(requireAuth())// Apply middleware to a specific route// Redirects to the homepage if the user is not authenticatedapp.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 varsapp.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 variableapp.get('/protected',requireAuth({ signInUrl:'/sign-in' }), (req, res) => {res.send('This is a protected route.')})// Start the server and listen on the specified portapp.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`)})
The getAuth() helper retrieves authentication state from the request object. See the Next.js reference documentationNext.js Icon for more examples 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'constapp=express()constPORT=3000// Apply `clerkMiddleware()` to all routesapp.use(clerkMiddleware())// Use `getAuth()` to protect a route based on authorization statusconsthasPermission= (req, res, next) => {constauth=getAuth(req)// Handle if the user is not authorizedif (!auth.has({ permission:'org:admin:example' })) {returnres.status(403).send('Forbidden') }returnnext()}// Use `requireAuth()` to protect this route// If user is not authenticated, requireAuth() will redirect back to the homepageapp.get('/path',requireAuth(), hasPermission, (req, res) =>res.json(req.auth))// Start the server and listen on the specified portapp.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`)})
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'constapp=express()app.get('/path', (req, res) => {// Use `getAuth()` to protect a route based on token typeconstauthObject=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) }})
Clerk's JavaScript Backend SDKClerk Icon 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 documentationClerk Icon for more 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()Clerk Icon to get the current user's UserJavaScript Icon object. If not authenticated, the request is rejected with a 401 status code.
import { clerkClient, requireAuth } from'@clerk/express'import express from'express'constapp=express()constPORT=3000app.get('/user',async (req, res) => {// Get the `userId` from the `Auth` objectconstuserId=req.auth.userId// If user isn't authenticated, return a 401 errorif (!userId) {res.status(401).json({ error:'User not authenticated' }) }// Use `clerkClient` to access Clerk's Backend SDK methods// and get the user's User objectconstuser=awaitclerkClient.users.getUser(userId)res.json(user)})// Start the server and listen on the specified portapp.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`)})