Skip to main content
Docs

clerkMiddleware()

The clerkMiddleware() function 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. It's must be set before any other middleware.

Tip

Even if you are using requireAuth() middleware, you should still use clerkMiddleware() as it will provide authentication state to routes that don't use requireAuth(). See the example.

import { clerkMiddleware } from '@clerk/express'

const app = express()

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

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

Example: Use clerkMiddleware(), requireAuth(), and getAuth() together

The following example demonstrates how to use clerkMiddleware(), requireAuth(), and getAuth() together. clerkMiddleware() will provide authentication state to routes that don't use requireAuth(), requireAuth() will provide authentication state to a route and also protect the route based on authentication status, and getAuth() can be used in a number of ways. In this example, getAuth() is used 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 a route based on authentication status
// If user is not authenticated, requireAuth() will redirect back to the homepage
// Then, use the `hasPermission` function created above to protect the route based on authorization status
app.get('/path', requireAuth(), hasPermission, (req, res) => res.json(req.auth))

// This route is not protected but it will have authentication state
// attached to the request object because `clerkMiddleware()` was applied to all routes
app.get('/path2', (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}`)
})

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.

  • 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 in the session (e.g., as reported by ) 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.

  • Name
    clerkClient
    Type
    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 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.

Feedback

What did you think of this content?

Last updated on