Docs

Handling requests with the Node SDK

Caution

On January 8, 2025, the Node SDK will no longer be available. Upgrade to the Express SDK.

Node SDK Middleware

The Clerk Node SDK offers two authentication middlewares specifically for Express and Connect/Express compatible frameworks such as Fastify.

ClerkExpressWithAuth()

ClerkExpressWithAuth() is a lax middleware that returns an empty auth object when an unauthenticated request is made.

import 'dotenv/config' // To read CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY
import { ClerkExpressWithAuth } from '@clerk/clerk-sdk-node'
import express from 'express'

const port = process.env.PORT || 3000

const app = express()
// Use the lax middleware that returns an empty auth object when unauthenticated
app.get(
  '/protected-endpoint',
  ClerkExpressWithAuth({
    // Add options here
    // See the Middleware options section for more details
  }),
  (req, res) => {
    res.json(req.auth)
  },
)

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
import 'dotenv/config' // To read CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY
import { ClerkExpressWithAuth, LooseAuthProp, WithAuthProp } from '@clerk/clerk-sdk-node'
import express, { Application, Request, Response } from 'express'

const port = process.env.PORT || 3000

const app: Application = express()

declare global {
  namespace Express {
    interface Request extends LooseAuthProp {}
  }
}

// Use the lax middleware that returns an empty auth object when unauthenticated
app.get(
  '/protected-route',
  ClerkExpressWithAuth({
    // Add options here
    // See the Middleware options section for more details
  }),
  (req: WithAuthProp<Request>, res: Response) => {
    res.json(req.auth)
  },
)

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(401).send('Unauthenticated!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

ClerkExpressRequireAuth()

ClerkExpressRequireAuth() is a strict middleware that raises an error when an unauthenticated request is made.

import 'dotenv/config' // To read CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node'
import express from 'express'

const port = process.env.PORT || 3000
const app = express()

// Use the strict middleware that raises an error when unauthenticated
app.get(
  '/protected-endpoint',
  ClerkExpressRequireAuth({
    // Add options here
    // See the Middleware options section for more details
  }),
  (req, res) => {
    res.json(req.auth)
  },
)

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(401).send('Unauthenticated!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
import 'dotenv/config' // To read CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY
import { ClerkExpressRequireAuth, RequireAuthProp, StrictAuthProp } from '@clerk/clerk-sdk-node'
import express, { Application, Request, Response } from 'express'

const port = process.env.PORT || 3000
const app: Application = express()

declare global {
  namespace Express {
    interface Request extends StrictAuthProp {}
  }
}

// Use the strict middleware that raises an error when unauthenticated
app.get(
  '/protected-route',
  ClerkExpressRequireAuth({
    // Add options here
    // See the Middleware options section for more details
  }),
  (req: RequireAuthProp<Request>, res) => {
    res.json(req.auth)
  },
)

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(401).send('Unauthenticated!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Express error handlers

Express comes with a default error handler for errors encountered in the middleware chain.

Developers can also implement their own custom error handlers as detailed in the Express error handling guide. An example error handler can be found above.

If you are using the strict middleware variant, the err passed to your error handler will contain enough context for you to respond as you deem fit.

Middleware options

These options can be used with both ClerkExpressWithAuth and ClerkExpressRequireAuth.

  • 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
    jwtKey
    Type
    string
    Description

    Used to verify the session token in a networkless manner. Supply the PEM public key from the API Keys page -> Show JWT public key -> PEM Public Key section of the Clerk Dashboard. It's recommended to use the environment variable instead. For more information, refer to Manual JWT verification.

  • Name
    onError
    Type
    (error: ClerkAPIResponseError) => unknown
    Description

    This function can act as a custom error handler tailored to the needs of your application.

  • Name
    signInUrl
    Type
    string
    Description

    The URL to redirect to when the user is not authenticated.

| isSatellite | boolean \| (url: URL) => boolean | When using Clerk's satellite feature, this should be enabled for secondary domains. | | domain | string \| (url: URL) => boolean | The domain used for satellites to inform Clerk where this application is deployed. | | proxyUrl | string | If using a proxy, specify the URL of the proxy. |

Feedback

What did you think of this content?

Last updated on