Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add middleware to a group of routes in Nuxt

Tags:

nuxt.js

According to the docs: The middleware will be executed in series in this order:

  • nuxt.config.js
  • Matched layouts
  • Matched pages

Now I was wondering how I can add middleware to a group of pages in a slug like this:

pages/
--| _slug/
-----| comments.vue
-----| index.vue

Some options I think there are:

1) I could add the middleware to every individual page in the directory but that's not dry.

2) Another solution would be to add the middleware to the nuxt.config.js with a conditional on the route, but that doesn't feel like the right place for that code either, besides that it would run on any other route too.

3) I could maybe use nested routes with a template containing only a single <nuxt-child> element, but I'm not sure about the side effects: Can I still use page-component properties? Does that nest everything in another DOM element?.

Any help is appreciated.

like image 985
Raymundus Avatar asked Oct 28 '25 07:10

Raymundus


1 Answers

Ok just figured my 'option 3' is the way to go here:

Create a file _slug.vue and add it to pages at the same nesting level as the _slug/ directory:

pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| _slug.vue

Add the middleware property in that _slug.vue file:

<template>
  <nuxt-child/>
</template>

<script>
export default {
  middleware: 'myslugmiddleware',
}
</script>
like image 127
Raymundus Avatar answered Oct 31 '25 11:10

Raymundus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!