āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā š shadcn/directory/clerk/clerk-docs/guides/secure/protect-pages ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā
This guide demonstrates how to protect pages in your Nuxt application.
[!TIP] To learn how to protect API routes, see the dedicated guide.
The useAuth() composable provides access to the current user's authentication state and methods to manage the active session. It also includes the isSignedIn property to check if the active user is signed in, which is helpful for protecting a page.
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.
In your middleware/ directory, create a file named auth.global.ts with the following code. This middleware:
isSignedIn property returned by the useAuth() composable to check if the user is signed in.createRouteMatcher() helper to check if the user is trying to access a protected route. If they are but they aren't signed in, they are redirected to the sign-in page.// Define the routes you want to protect with `createRouteMatcher()`
const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/forum(.*)'])
export default defineNuxtRouteMiddleware((to) => {
// Use the `useAuth()` composable to access the `isSignedIn` property
const { isSignedIn } = useAuth()
// Check if the user is not signed in and is trying to access a protected route
// If so, redirect them to the sign-in page
if (!isSignedIn.value && isProtectedRoute(to)) {
return navigateTo('/sign-in')
}
})
ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā