Protect pages in your Nuxt app with Clerk
There are two ways to protect pages in your Nuxt application:
The useAuth()
composable provides access to the current user's authentication state and methods to manage the active session. You can use this composable to protect pages.
In the following example, the isLoaded
property checks if Clerk has finished initializing and the userId
property checks if the user is signed in.
Use defineNuxtRouteMiddleware()
The defineNuxtRouteMiddleware()
utility function helps protect pages in your Nuxt application by validating authentication on the client-side. This middleware integrates seamlessly with Clerk authentication.
Configure defineNuxtRouteMiddleware()
In your middleware/
directory, create a file named auth.ts
with the following code. This middleware uses the useAuth()
composable to check if the user is signed in. If they aren't, the middleware redirects them to the sign-in page.
Protect pages with defineNuxtRouteMiddleware()
To protect a page, add the middleware to the definePageMeta()
function. In the last step, you stored the middleware in the auth.ts
file, so you would pass auth
in the middleware
array.
Feedback
Last updated on