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 pagesNuxt.js Icon.
In the following example, the isLoaded property checks if Clerk has finished initializing and the userId property checks if the user is signed in.
pages/protected-page.vue
<scriptsetup>const { userId,isLoaded } =useAuth()</script><template> <divv-if="!isLoaded">Loading...</div> <divv-else-if="!userId">Sign in to access this page</div> <divv-else>Hello, {{ userId }}!</div></template>
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:
Uses the userId returned by the useAuth()Vue.js Icon 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.
middleware/auth.global.ts
constisProtectedRoute=createRouteMatcher(['/dashboard(.*)','/forum(.*)'])exportdefaultdefineNuxtRouteMiddleware((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 pageif (!userId.value &&isProtectedRoute(to)) {returnnavigateTo('/sign-in') }})