mirror of
https://github.com/nuxt/nuxt.git
synced 2025-02-20 07:30:57 +00:00
docs: add explanation for middleware execution order (#20029)
This commit is contained in:
parent
2f8e991b94
commit
66d76c3d36
@ -58,6 +58,59 @@ 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.
|
||||
::
|
||||
|
||||
## What Order Middleware Runs In
|
||||
|
||||
Middleware runs in the following order:
|
||||
|
||||
1. Global Middleware
|
||||
2. Page defined middleware order (if there are multiple middleware declared with the array syntax)
|
||||
|
||||
For example, assuming you have the following middleware and component:
|
||||
|
||||
```text [middleware/ directory]
|
||||
middleware/
|
||||
--| analytics.global.ts
|
||||
--| setup.global.ts
|
||||
--| auth.ts
|
||||
```
|
||||
|
||||
```vue [pages/profile.vue]
|
||||
<script setup>
|
||||
definePageMeta({
|
||||
middleware: [
|
||||
function (to, from) {
|
||||
// Custom inline middleware
|
||||
},
|
||||
"auth",
|
||||
],
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
You can expect the middleware to be run in the following order:
|
||||
|
||||
1. `analytics.global.ts`
|
||||
2. `setup.global.ts`
|
||||
3. Custom inline middleware
|
||||
4. `auth.ts`
|
||||
|
||||
### Ordering global middleware
|
||||
|
||||
By default, global middleware is executed alphabetically based on the filename.
|
||||
|
||||
However, there may be times you want to define a specific order. For example, in the last scenario, `setup.global,ts` may need to run before `analytics.global.ts`. In that case, we recommend prefixing global middleware with "alphabetical" numbering.
|
||||
|
||||
```text [middleware/ directory]
|
||||
middleware/
|
||||
--| 01.setup.global.ts
|
||||
--| 02.analytics.global.ts
|
||||
--| auth.ts
|
||||
```
|
||||
|
||||
::alert{type=info icon=💡}
|
||||
In case you're new to "alphabetical" numbering, remember that filenames are sorted as strings as not as numeric values. For example, `10.new.global.ts` would come before `2.new.global.ts`. This is why the example prefixes single digit numbers with `0`.
|
||||
::
|
||||
|
||||
## 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.
|
||||
|
Loading…
Reference in New Issue
Block a user