diff --git a/docs/2.guide/2.directory-structure/1.middleware.md b/docs/2.guide/2.directory-structure/1.middleware.md index 4441ff74796..9ba35579158 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.