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
clerkMiddleware()
The clerkMiddleware() middleware checks the request's cookies and headers for a session JWT and if found, attaches the Authrequest object under the auth key. See the reference doc for more information.
requireAuth()
The requireAuth() middleware acts similarly to clerkMiddleware(), but also protects your routes by redirecting unauthenticated users to the homepage. See the reference doc for more information.
getAuth()
The getAuth() helper retrieves authentication state from the request object. It returns the Auth object
clerkClient
Clerk's JS Backend SDKusers.getUserList() method from the JS Backend SDK instead of manually making a fetch request to the https://api.clerk.com/v1/users endpoint.
To access a resource, you must first instantiate a clerkClient instance. See the reference documentation
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()401 status code.
import { clerkClient, clerkMiddleware, getAuth } from '@clerk/express'
import express from 'express'
const app = express()
const PORT = 3000
// Apply `clerkMiddleware()` to all routes
app.use(clerkMiddleware())
app.get('/user', async (req, res) => {
// Use `getAuth()` to access `isAuthenticated` and the user's ID
const { isAuthenticated, userId } = getAuth(req)
// If user isn't authenticated, return a 401 error
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Use `clerkClient` to access Clerk's JS 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