clerkMiddleware()
| Astro
The clerkMiddleware()
helper integrates Clerk authentication into your Astro application through middleware.
Configure clerkMiddleware()
Create a middleware.ts
file inside your src/
directory.
createRouteMatcher()
createRouteMatcher()
is a Clerk helper function that allows you to protect multiple routes. createRouteMatcher()
accepts an array of routes and checks if the route the user is trying to visit matches one of the routes passed to it.
The createRouteMatcher()
helper returns a function that, if called with the context.request
object from the Middleware, will return true
if the user is trying to access a route that matches one of the routes passed to createRouteMatcher()
.
In the following example, createRouteMatcher()
sets all /dashboard
and /forum
routes as protected routes.
Protect routes
You can protect routes by checking either or both of the following:
- User authentication status -- user is signed in or out
- User authorization status -- user has the required role or permission
Protect routes based on user authentication status
To protect routes based on user authentication status, use auth().userId
to check if the userId
is present. If it is not, the user is not authenticated, and you can redirect them to the sign-in page.
Protect routes based on user authorization status
To protect routes based on user authorization status, use auth().has()
to check if the user has the required roles or permissions.
Protect all routes
To protect all routes in your application and define specific routes as public, you can use any of the above methods and simply invert the if
condition.
clerkMiddleware()
options
The clerkMiddleware()
function accepts an optional object. See the full list of options available here
Feedback
Last updated on