Express Quickstart
You will learn the following:
- Install
@clerk/express
- Set your Clerk API keys
- Add
clerkMiddleware()
to your application - Protect your routes using
requireAuth()
Before you start
Example repository
Learn how to integrate Clerk into your Express backend for secure user authentication and management. This guide focuses on backend implementation and requires a Clerk frontend SDK to function correctly.
Install @clerk/express
Clerk's Express SDK gives you access to prebuilt components, React hooks, and helpers to make user authentication easier.
Run the following command to install the SDK:
Add the following keys to your .env
file. These keys can always be retrieved from the API keys page in the Clerk Dashboard.
- In the Clerk Dashboard, navigate to the API keys page.
- In the Quick Copy section, copy your Clerk Publishable and Secret Keys.
- Paste your keys into your
.env
file.
The final result should resemble the following:
This guide uses dotenv
to load the environment variables. Run the following command to install it:
Add clerkMiddleware()
to your app
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.
Protect your routes using requireAuth()
To protect your routes, use the requireAuth()
middleware. This middleware functions similarly to clerkMiddleware()
, but also protects your routes by redirecting unauthenticated users to the sign-in page.
In the following example, requireAuth()
is used to protect the /protected
route. If the user isn't authenticated, they're redirected to the homepage. If the user is authenticated, the getAuth()
function is used to get the userId
, which is passed to clerkClient.users.getUser()
to fetch the current user's User
object.
Add global TypeScript type (optional)
If you're using TypeScript, add a global type reference to your project to enable auto-completion and type checking for the auth
object in Express request handlers.
- In your application's root folder, create a
types/
directory. - Inside this directory, create a
globals.d.ts
file with the following code.
Use middleware to protect routes
Learn how to protect specific routes from unauthenticated users.
Protect routes based on authorization status
Learn how to protect a route based on both authentication and authorization status.
Express SDK reference
Learn more about additional Express SDK methods.
Deploy to Production
Learn how to deploy your Clerk app to production.
Feedback
Last updated on