docs: add information on when mw runs & how to skip (#19083)

This commit is contained in:
Daniel Roe 2023-02-16 12:27:28 +00:00 committed by GitHub
parent a937e847f4
commit a1252d3a30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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.