How to implement multiple middlewares in vue.js 3?

Member

by darion , in category: Javascript , a year ago

How to implement multiple middlewares in vue.js 3?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@darion 

In Vue.js 3, you can implement multiple middlewares by using the composition API and Vue Router. Here's an example of how you can do it:

  1. Install Vue Router by running the following command:
1
npm install vue-router@next


  1. Create a new file called router.js and import the necessary dependencies:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Dashboard from './views/Dashboard.vue'

// Import your middlewares
import middleware1 from './middlewares/middleware1'
import middleware2 from './middlewares/middleware2'

// Create the router instance
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: Home,
      beforeEnter: middleware1, // Apply middleware1 to this route
    },
    {
      path: '/dashboard',
      component: Dashboard,
      beforeEnter: [middleware1, middleware2], // Apply both middleware1 and middleware2 to this route
    },
  ],
})

export default router


  1. Create separate middleware files for each middleware function you want to implement. For example, create a new folder called middlewares and inside it, create middleware1.js and middleware2.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// middleware1.js
export default function middleware1(to, from, next) {
  // Implement your middleware logic here
  console.log('middleware1')
  next()
}

// middleware2.js
export default function middleware2(to, from, next) {
  // Implement your middleware logic here
  console.log('middleware2')
  next()
}


  1. Import and use the router instance in your main Vue.js app file:
1
2
3
4
5
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')


With this setup, each time a route is navigated to, the corresponding middleware function(s) will be executed before the route component is rendered. Note that the next function is called to proceed to the next middleware or to the route itself.


You can add as many middlewares as you need by supplying an array of middleware functions in the beforeEnter property of the route configuration.