From ae2cf03bc5bbedd098b7059b8c49ca2bf9a7a5e7 Mon Sep 17 00:00:00 2001 From: thehouseisonfire <141861234+thehouseisonfire@users.noreply.github.com> Date: Mon, 29 Jan 2024 17:47:51 -0300 Subject: [PATCH] docs: redirect loop warn (#1487) * avoid infinite redirect * chore: review --------- Co-authored-by: Eduardo San Martin Morote --- docs/nuxt/auth.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/nuxt/auth.md b/docs/nuxt/auth.md index ccf5f6f6..673c18f4 100644 --- a/docs/nuxt/auth.md +++ b/docs/nuxt/auth.md @@ -54,6 +54,24 @@ definePageMeta({ ``` +::: warning + +If you are using a [global middleware](https://nuxt.com/docs/getting-started/routing#route-middleware), make sure **you are not getting into a redirect loop** by ensuring `navigateTo()` is only called if the target location is not the same page: + +```ts{4} +// middleware/auth.global.ts +export default defineNuxtRouteMiddleware(async (to, from) => { + // ... + if (!user && to.path !== '/login') { + return navigateTo({ path: '/login' }) + } +}) +``` + +::: + +````vue{2-4} + You can even automatically handle the auth state by _watching_ the current user. We recommend you do this in either a layout or the `app.vue` component so the watcher is always active: ```vue