clerkMiddleware() | Nuxt
The clerkMiddleware()
helper allows you to protect your Nuxt application on the server-side. It can be used to validate a user's authentication status or authorization status.
Configure clerkMiddleware()
By default, the Nuxt SDK automatically adds the clerkMiddleware()
helper to your Nuxt application.
To manually configure the middleware:
-
In your
nuxt.config.ts
file, under theclerk
property, setskipServerMiddleware: true
. -
In your
server/middleware/
directory, create a file namedclerk.ts
with the following code:
Protect API routes
You can protect routes using either or both of the following:
- Authentication-based protection: Verify if the user is signed in.
- Authorization-based protection: Verify if the user has the required organization roles or custom permissions.
Authentication-based protection
To protect routes based on user authentication status, you can check if the user is signed in by checking the userId
on the auth
object.
In the following example, the clerkMiddleware()
helper checks if the user is signed in and accessing a protected route. If they aren't signed in, an error is thrown using Nuxt's createError()
utility.
Authorization-based protection
To protect routes based on user authorization status, you can use the has()
helper to check if the user has the required organization roles or custom permissions. It is available on the auth
object.
Protecting routes using custom permissions
In the following example, the clerkMiddleware()
helper checks if the user is accessing a protected route. If so, it checks if the user has the required custom permission. If they don't, an error is thrown using Nuxt's createError()
utility.
In the following example, the clerkMiddleware()
helper checks if the user is accessing a protected route. If so, it checks if the user has the required admin role. If they don't, an error is thrown using Nuxt's createError()
utility.
Feedback
Last updated on