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.
<script setup>
const { userId, isLoaded } = useAuth()
</script>
<template>
<div v-if="!isLoaded">Loading...</div>
<div v-else-if="!userId">Sign in to access this page</div>
<div v-else>Hello, {{ userId }}!</div>
</template>
Use createRouteMatcher()
The createRouteMatcher()
is a Clerk helper function that allows you to protect multiple routes in your Nuxt application. It accepts an array of route patterns and checks if the route the user is trying to visit matches one of the patterns passed to it.
The createRouteMatcher()
helper returns a function that, when called with the to
route object from Nuxt's defineNuxtRouteMiddleware()
, will return true
if the user is trying to access a route that matches one of the patterns provided.
Configure route middleware
In your middleware/
directory, create a file named auth.global.ts
with the following code. This middleware:
- Uses the
userId
returned by theuseAuth()
composable to check if the user is signed in - Uses the
createRouteMatcher()
helper to check if the user is trying to access a protected route.
If they aren't signed in and are trying to access a protected route, they are redirected to the sign-in page.
const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/forum(.*)'])
export default defineNuxtRouteMiddleware((to) => {
const { userId } = useAuth()
// If the user is not signed in, they aren't allowed to access
// the protected route and are redirected to the sign-in page
if (!userId.value && isProtectedRoute(to)) {
return navigateTo('/sign-in')
}
})
Feedback
Last updated on