From a1252d3a30b13eb067e8ee489c497359803e3309 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Thu, 16 Feb 2023 12:27:28 +0000 Subject: [PATCH] docs: add information on when mw runs & how to skip (#19083) --- .../2.directory-structure/1.middleware.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/2.guide/2.directory-structure/1.middleware.md b/docs/2.guide/2.directory-structure/1.middleware.md index 4441ff7479..9ba3557915 100644 --- a/docs/2.guide/2.directory-structure/1.middleware.md +++ b/docs/2.guide/2.directory-structure/1.middleware.md @@ -58,6 +58,24 @@ Unlike navigation guards in [the vue-router docs](https://router.vuejs.org/guide We recommend using the helper functions above for performing redirects or stopping navigation. Other possible return values described in [the vue-router docs](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards) may work but there may be breaking changes in future. :: +## When Middleware Runs + +If your site is server-rendered or generated, middleware for the initial page will be executed both when the page is rendered and then again on the client. This might be needed if your middleware needs a browser environment, such as if you have a generated site, aggressively cache responses, or want to read a value from local storage. + +However, if you want to avoid this behaviour you can do so: + +```js +export default defineNuxtRouteMiddleware(to => { + // skip middleware on server + if (process.server) return + // skip middleware on client side entirely + if (process.client) return + // or only skip middleware on initial client load + const nuxtApp = useNuxtApp() + if (process.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) return +}) +``` + ## Adding Middleware Dynamically It is possible to add global or named route middleware manually using the `addRouteMiddleware()` helper function, such as from within a plugin.