requireAuth()
The requireAuth()
middleware functions similarly to clerkMiddleware()
, in that it 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. However, its difference is that it 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 { clerkMiddleware, requireAuth } from '@clerk/express'
import express from 'express'
const app = express()
const PORT = 3000
// Apply middleware to all routes
app.use(clerkMiddleware())
app.use(requireAuth())
// Apply middleware to a specific route
// Redirects to the homepage if the user is not authenticated
app.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 vars
app.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 variable
app.get('/protected', requireAuth({ signInUrl: '/sign-in' }), (req, res) => {
res.send('This is a protected route.')
})
// Start the server and listen on the specified port
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})
requireAuth()
options
requireAuth()
accepts the same options as clerkMiddleware()
.
Feedback
Last updated on