---
title: "Protect pages and routes"
description: "Open a page only to the right people with definePageMeta({ auth }): signed in, an app-wide role, a workspace, a plan feature. Anyone else gets a 403 that shows <AccessDenied>, or a 404 for a hidden page. Also: when a session ends, and server routes."
canonical_url: "https://nuxt-backend.dev/docs/build/auth/access/pages"
---
# Protect pages and routes

> Open a page only to the right people with definePageMeta({ auth }): signed in, an app-wide role, a workspace, a plan feature. Anyone else gets a 403 that shows <AccessDenied>, or a 404 for a hidden page. Also: when a session ends, and server routes.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/strips)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/runtime/vue/utils/page-access.ts)

A page says who may open it in its own `definePageMeta({ auth })`. That is the one page guard: there is no middleware to name. The module checks the rules before the page renders, on the server for a page loaded directly and in the browser for a navigation. A signed-out visitor goes to the sign-in page. A signed-in person without access gets a 403 with [`<AccessDenied>`](#the-403-page), or a 404 when the page is hidden.

Page rules decide what the screen shows. They protect no data: every function the page calls checks the caller too ([Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions)).

## Ask for a sign-in

A page that needs a signed-in person says `auth: true`:

```vue [app/pages/studio.vue]
<script setup lang="ts">
definePageMeta({ auth: true })
</script>
```

A signed-out visitor goes to the sign-in page (`/login`, or wherever [`pages.login`](https://nuxt-backend.dev/docs/reference/configuration/module-options) puts it) with the page they wanted in `?redirect=`. After sign-in they land back there. When `?redirect=` names no page of this site, they land on [`redirects.afterSignIn`](https://nuxt-backend.dev/docs/reference/configuration/module-options) (`/` by default):

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['nuxt-backend'],
  backend: {
    redirects: { afterSignIn: '/studio' },
  },
})
```

## Ask for a role, a workspace or a plan feature

Give `auth` an object of rules. A page with rules asks for a sign-in too. An app-wide role:

```vue [app/pages/editor/queue.vue]
<script setup lang="ts">
definePageMeta({
  auth: { role: ['admin', 'editor'] },
})
</script>
```

A role in the active workspace. `workspace: true` lets in any member, and a role or a list lets in only those who hold it there:

```vue [app/pages/studio/billing.vue]
<script setup lang="ts">
definePageMeta({
  auth: { workspace: ['owner', 'admin'] },
})
</script>
```

A feature of the active workspace's plan, by its key in your [catalog](https://nuxt-backend.dev/docs/build/billing/subscriptions/feature-gating):

```vue [app/pages/studio/export.vue]
<script setup lang="ts">
definePageMeta({
  auth: { workspace: true, feature: 'hd_export' },
})
</script>
```

<table>
<thead>
  <tr>
    <th>
      Rule
    </th>
    
    <th>
      Passes when
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        role
      </code>
    </td>
    
    <td>
      The app-wide role is the one given, or one of a list (<code>
        ['admin', 'editor']
      </code>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        workspace
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
      
      : the person has an active workspace they belong to. A role or a list (<code>
        'owner'
      </code>
      
      , <code>
        ['owner', 'admin']
      </code>
      
      ): they hold it there.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        feature
      </code>
    </td>
    
    <td>
      The active workspace's plan includes the feature.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        hidden
      </code>
    </td>
    
    <td>
      Changes no check. With <code>
        true
      </code>
      
      , a refused person gets a 404 instead of the 403, and so does a signed-out visitor instead of the sign-in page, so the page's existence stays private.
    </td>
  </tr>
</tbody>
</table>

- **Every rule must pass.** `role: 'admin'` with `workspace: 'owner'` asks for both.
- **A parent's rules hold for its children.** Rules on `pages/admin.vue` guard `pages/admin/strips.vue`, which can add its own.
- **A key that names no rule refuses the page.** A misspelled `roles` would otherwise open the page to everyone signed in. Development names the key in a warning.
- **A banned account** is refused every page with rules.
- **The workspace is read fresh** from the auth server on each guarded navigation, so a person removed from a workspace is refused on their next page.

### Hide a page from everyone else

An admin-only page that nobody else should know about adds `hidden: true` to its rules. Anyone the rules refuse gets a 404, the same as for a page that doesn't exist, and a signed-out visitor too, so even the sign-in page never says it is there:

```vue [app/pages/admin/featured.vue]
<script setup lang="ts">
definePageMeta({
  auth: { role: 'admin', hidden: true },
})
</script>
```

Your own admin tabs use exactly that ([Add your own admin tabs](https://nuxt-backend.dev/docs/build/auth/admin/custom-tabs)).

## What a person sees

<table>
<thead>
  <tr>
    <th>
      Who
    </th>
    
    <th>
      What happens
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Signed out
    </td>
    
    <td>
      Sent to the sign-in page, with <code>
        ?redirect=
      </code>
      
       back to the page. A one-time code in the page's address never rides along. A hidden page answers 404 instead.
    </td>
  </tr>
  
  <tr>
    <td>
      Signed in, failing a rule
    </td>
    
    <td>
      A 403. A direct load answers with status 403 and the error page. A navigation shows the same page and keeps the page's path in the address bar.
    </td>
  </tr>
  
  <tr>
    <td>
      Signed in, failing a rule of a hidden page
    </td>
    
    <td>
      A 404, the same as for a page that doesn't exist.
    </td>
  </tr>
  
  <tr>
    <td>
      Signed in, passing every rule
    </td>
    
    <td>
      The page.
    </td>
  </tr>
</tbody>
</table>

The 403 is a fatal Nuxt error. Its `data` says which rule failed and which page was asked for, never the role or the feature the page wants:

<table>
<thead>
  <tr>
    <th>
      <code>
        error.data.reason
      </code>
    </th>
    
    <th>
      The person
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        role
      </code>
    </td>
    
    <td>
      Lacks the app-wide role.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        workspace
      </code>
    </td>
    
    <td>
      Has no active workspace, or another role in it.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        feature
      </code>
    </td>
    
    <td>
      Has a workspace whose plan lacks the feature.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        banned
      </code>
    </td>
    
    <td>
      Is banned.
    </td>
  </tr>
</tbody>
</table>

`error.data.path` is the page asked for, a path of your site. Both are typed: `import type { AccessDeniedData } from 'nuxt-backend'`.

## The 403 page

An app without an `error.vue` of its own needs nothing more. The module's error page shows a 403 with `<AccessDenied>`, and every other error as Nuxt's own page does.

Your own `error.vue` replaces the module's. Render `<AccessDenied>` for a 403 there, and your own markup for everything else:

```vue [app/error.vue]
<script setup lang="ts">
import type { NuxtError } from '#app'
import type { AccessDeniedData } from 'nuxt-backend'

const props = defineProps<{ error: NuxtError<AccessDeniedData> }>()

useHead({ title: () => (props.error.status === 403 ? 'No access' : 'Something went wrong') })
</script>

<template>
  <main>
    <AccessDenied v-if="error.status === 403" :error="error" home="/studio" />
    <section v-else>
      <h1>{{ error.status }}</h1>
      <button type="button" @click="clearError({ redirect: '/' })">Go home</button>
    </section>
  </main>
</template>
```

`<AccessDenied>` says why, in the words of the rule that failed, names who is signed in, and offers the ways on:

- **Go to the home page**: the `home` prop, or `redirects.afterSignIn` without one.
- **Switch workspace**, for a workspace rule: the settings page, where the switcher is.
- **See plans**, for a feature rule: the pricing page.
- **Sign in with another account**: signs out, then back to sign in with `?redirect=` to the page.

Its words are the `access` [labels](https://nuxt-backend.dev/docs/build/ui/customize/labels), and its `title`, `message` and `actions` slots each replace one region ([`<AccessDenied>`](https://nuxt-backend.dev/docs/reference/components/shell#accessdenied)).

## When the session ends

Page rules run on navigation. A session can also end while a guarded page is open: a sign-out in another tab, or a session revoked from another device. The module then sends the person to the sign-in page, with `?redirect=` back to the page they were on. It waits for the auth server's settled answer, so a page that is still hydrating or refreshing its token is left alone.

A sign-out through `useAuth().signOut()` in this tab is yours to follow: navigate where you want after it. The module adds no `?redirect=` for it, so whoever signs in next on this browser is never sent to the last person's page.

To decide yourself, handle the `backend:session-ended` hook in a plugin. Set `to` to send the person elsewhere, or call `preventDefault()` to keep them on the page:

```ts [app/plugins/session-ended.client.ts]
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('backend:session-ended', (context) => {
    // An editor keeps its page: it saves the draft, then asks to sign in again.
    if (context.route.path.startsWith('/studio/edit')) context.preventDefault()
    else context.to = '/signed-out'
  })
})
```

A public page is left alone, whatever the hook does.

## Show parts of a page by auth state

To show part of a page rather than guard all of it, wrap the part in `<Gate>`. It takes the same checks as page rules, as props, and renders its `#fallback` slot to anyone who fails them:

```vue [app/components/StudioHeader.vue]
<template>
  <Gate signed-in>
    <StudioMenu />
    <template #fallback>
      <NuxtLink to="/login">Sign in</NuxtLink>
    </template>
  </Gate>
</template>
```

`<Gate>` also takes `role`, `workspace`, `feature` and `quota`. It gates what the screen shows, never data. [Show parts of a page to the right people](https://nuxt-backend.dev/docs/build/ui/gate) covers it in full. For a loading state, `useAuth().isLoading` says whether the session is still resolving.

## Guard a server route

A Nitro route of your app checks the request's session with `backendAuth(event)`, auto-imported in `server/`. It reads the session cookie, fetches the Convex token and calls your functions as the signed-in person:

```ts [server/api/me.get.ts]
import { api } from '#backend/api'

export default defineEventHandler(async (event) => {
  const auth = backendAuth(event)
  if (!await auth.isAuthenticated()) throw createError({ statusCode: 401 })
  return auth.fetchAuthQuery(api.auth.getAuthUser, {})
})
```

The function it calls still checks the caller. The route's check decides the HTTP answer, and the function's check protects the data. [Server utilities](https://nuxt-backend.dev/docs/reference/nuxt/server-utilities#backendauthevent) lists every helper.

## Where the rules are checked

- **A direct load** decides on the server, from the session token the server fetched for the request. A `workspace` rule also reads the member row through your auth route.
- **A navigation in the browser** decides from the session the auth client holds, once it has loaded.
- **A role taken away while the page is open** is noticed on the next navigation. A session that ends is noticed at once ([When the session ends](#when-the-session-ends)).
- **Caches never hold a guarded page.** A render for one person carries their session in its payload. So every page with rules gets the route rules of a private page: never prerendered, `cache`, `swr` and `isr` off, `cache-control: private, no-store`, and kept out of search indexes. Keep an app-wide `swr`, `isr` or `cache` rule off those paths ([Caches](https://nuxt-backend.dev/docs/build/ui/pages#caches)). The module warns at startup when one covers a guarded page.

## Verify

1. Sign in with an account that is not an admin, then open a page with `auth: { role: 'admin' }` from a link. Your error page shows the 403.
2. Reload the page. The response itself is a 403, as the browser's network panel shows.
3. Add `hidden: true` beside the role and reload. The page answers 404.
4. Sign out and open the page again. You land on the sign-in page with `?redirect=` back to it.

## Related

- [Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions): the same checks on the server, where they protect data.
- [Give people roles](https://nuxt-backend.dev/docs/build/auth/access/roles): the roles a `role` rule reads.
- [Gate features by plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/feature-gating): the features a `feature` rule reads.
- [Sign users in](https://nuxt-backend.dev/docs/build/auth/sign-in): the page signed-out visitors land on.
- [Default pages](https://nuxt-backend.dev/docs/build/ui/pages): the pages the module mounts, and their rules.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
