Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 12 additions & 27 deletions docs/pages/4.advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,41 +24,26 @@ const { data, pending, refresh, error } = await useAsyncData(

## Auth middleware

You can protect your authenticated routes by creating a custom plugin in your project, here is an example:
You can protect your authenticated routes by creating a [custom middleware](https://v3.nuxtjs.org/docs/directory-structure/middleware/) in your project, here is an example:

```ts [plugins/auth.ts]
import type { Router, RouteLocationNormalized } from 'vue-router'

const authRoutes = ['dashboard']

export default defineNuxtPlugin((nuxtApp) => {
const router: Router = nuxtApp.$router
```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, _from) => {
const user = useStrapiUser()
const { ssrContext } = useNuxtApp()

const redirect = (to: RouteLocationNormalized) => {
if (authRoutes.includes(to.name as string) && !user.value) {
return '/login'
}
if (!user.value) {
useCookie('redirect', { path: '/' }).value = to.fullPath
return navigateTo('/login')
}
})
```

if (ssrContext) {
const { res, url } = ssrContext
const to = router.resolve(url)
Don't forget to reference your middleware in your page with:

const Location = redirect(to)
if (Location) {
res.writeHead(302, { Location })
res.end()
}
} else {
router.beforeEach(redirect)
}
```ts [pages/my-page.vue]
definePageMeta({
middleware: 'auth'
})
```

> Remember, your plugins are [auto-imported](https://v3.nuxtjs.org/docs/directory-structure/plugins) by Nuxt 3.

## Errors handling

You can use the nuxt `strapi:error` hook to display a toast for example (the following example assumes that a `$toast` plugin has been injected).
Expand Down