Skip to content

Commit

Permalink
docs: add information on when mw runs & how to skip (#19083)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Feb 16, 2023
1 parent a937e84 commit a1252d3
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions docs/2.guide/2.directory-structure/1.middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit a1252d3

Please sign in to comment.