Docs

Protect pages in your Nuxt app with Clerk

There are two ways to protect pages in your Nuxt application:

Note

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. 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.

pages/protected-page.vue
<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 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.

middleware/auth.ts
export default defineNuxtRouteMiddleware(() => {
  const { userId } = useAuth()

  // If the user is not signed in, redirect to the sign-in page
  if (!userId.value) {
    return navigateTo('/sign-in')
  }
})

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.

pages/dashboard.vue
<script setup lang="ts">
definePageMeta({
  // `auth` is the name of the middleware file
  middleware: ['auth'],
})
</script>

<template>
  <h1>Dashboard page</h1>
</template>

Feedback

What did you think of this content?

Last updated on