The Talent500 Blog
Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 1

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide

Introduction

One of the most widely used terminologies in web development is middleware, which acts as an intermediary between two applications or services. The strong idea of middleware assists developers with routing and related patterns.

Middleware in VueJS may be used for multiple layout switching, limiting some routes based on the user role, and so on. This blog will go through how to set up a middleware pipeline in VueJS and how to use several middleware on a single route.

Prerequisites to Implement Middleware Pipeline in VueJS

  1. Need to know the Basic knowledge of the working of VueJS
  2. Familiar with vue-router and navigation guards in Vue.js,

Create VueJS App

Create a VueJS project with the help of the vue-cli tool.

Vue creates vue-middleware-demo

Now you will be prompted to choose the Vue version, Now select vue-2.

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 2

vue-cli will install the dependencies after selecting the relevant version and now you can serve the project.

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 3

You have successfully created a new project,

Installing vue-router

Using the below command, install vue-route.

cd vue-middleware-demo

yarn add vue-router

Here we are using yarn

To serve the project use the below command.

yarn run serve

The default user interface will look something like this initially. In the next section, we configure the routers.

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 4

Creating Routes

We will set up some basic routes in this section. There will be two web pages in the demo application one for login and the other for the user’s profile.

The structure looks like this:

../vue-middleware-demo/src/pages/Login.vue

../vue-middleware-demo/src/pages/UserProfile.vue

For the demo application, Create a router.js file within the src directory to configure routes.

// router.js

import Vue from “vue”;

import VueRouter from “vue-router”;

import LoginPage from “@/pages/LoginPage.vue”

import UserProfile from “@/pages/UserProfile.vue”

import HelloWorld from “./components/HelloWorld”

Vue.use(VueRouter)

const appRoutes = [

   {

    path: ‘/’,

    name: ‘home’,

    component: HelloWorld

   },

   {

    path: ‘/login’,

    name: ‘login’,

    component: LoginPage

   },

   {

    path: ‘/user-profile’,

    name: ‘user.profile’,

    component: UserProfile

   }

]

const routes = […appRoutes]

const router = new VueRouter({

   mode: ‘history’,

   routes

})

export default router

Now we are almost done with the configuration. To make them accessible, add a router-view in App. vue.

// App.vue

<template>

 <div id=”app”>

   <img alt=”Vue logo” src=”./assets/logo.png”>

   <router-view></router-view> <!– Change: Add router view –>

 </div>

</template>

<script>

export default {

 name: ‘App’,

}

</script>

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 5

Learn How to Set Up and Use Middleware Pipeline in VueJS: A Step-by-Step Guide 6

Creating Middlewares

Here you will be creating the first middleware guest.js . it will be responsible for navigating to the user-profile page.

// guest.js

export default function guest({next,store}){

   let isLoggedIn = false // Can be calculated through store

   if(isLoggedIn){

    return next({

        name: ‘home’

    })

   }

   return next();

}

Create a middleware pipeline. It is responsible for communication between navigation guards and middleware.

After this, a file with the name middleware-pipeline.js is to be created. Then the user can use the code given below.

function middlewarePipeline (context, middleware, index) {

   const nextMiddleware = middleware[index]

   if(!nextMiddleware){

    return context.next

   }

   return () => {

    const nextPipeline = middlewarePipeline(

           context, middleware, index + 1

    )

       nextMiddleware({ …context, next: nextPipeline })

   }

}

export default middlewarePipeline

Configure it in router.js once you are done with this file. Then the navigation guard and the middleware pipeline can be used to execute middleware. The steps follow below.

// router.js

router.beforeEach((to, from, next) => {

   /** Navigate to next if middleware is not applied */

   if (!to.meta.middleware) {

    return next()

   }

   const middleware = to.meta.middleware;

   const context = {

  to,

  from,

  Next,

  //   store  | You can also pass store as an argument

   }

   return middleware[0]({

    …context,

    next:middlewarePipeline(context, middleware,1)

   })

 })

Here the connection is established now.

The next step is to configure the middleware in the appropriate path; for now implement guest middleware in /log in, which means that if the user is logged in, it will redirect the user from the Login page to the Home page.

Now add this middleware to the routes. Use the following code where you want to apply the middleware.

{

   path: ‘/login’,

   name: ‘login’,

   meta: {

   middleware: [

    guest

]

},

      component: LoginPage

 },

After all changes to router.js, the file should look like this.

// router.js

import Vue from “vue”;

import VueRouter from “vue-router”;

import LoginPage from “@/pages/LoginPage.vue”

import UserProfile from “@/pages/UserProfile.vue”

import HelloWorld from “./components/HelloWorld”

import guest from “./middleware/guest” // Change: Import Middleware

import middleware pipeline from “./middleware/middleware-pipeline”;

Vue.use(VueRouter)

const appRoutes = [

   {

    path: ‘/’,

    name: ‘home’,

       component: HelloWorld

   },

   {

    path: ‘/login’,

    name: ‘login’,

    meta: {

           middleware: [

               guest

        ]

    },

       component: LoginPage

   },

   {

    path: ‘/user-profile’,

    name: ‘user.profile’,

       component: UserProfile

   }

]

const routes = […appRoutes]

const router = new VueRouter({

   mode: ‘history’,

   routes

})

router.beforeEach((to, from, next) => {

   /** Navigate to next if middleware is not applied */

   if (!to.meta.middleware) {

    return next()

   }

   const middleware = to.meta.middleware;

   const context = {

  to,

  from,

  next,

   //   store  | You can also pass store as an argument

   }

   return middleware[0]({

       …context,

       next:middlewarePipeline(context, middleware,1)

   })

 })

export default router

Now navigate to http://localhost:8080/login, you will see that you are being redirected to Home Page or http://localhost:8080/ route.

Now you have successfully implemented a middleware pipeline in Vue.js.

Add multiple middlewares to the same routes.

Configure Multiple Middlewares

Remember, we have added extra metadata to the login route. This is how the path object will look like.

{

   path: ‘/login’,

   name: ‘login’,

   meta: {

      middleware: [

         guest

  ]

 },

   component: LoginPage

 },

Have you noticed the middleware key here?

Since this is a type of array, multiple middlewares can be passed on to the key.

So, let’s add another middleware called auth.js that will be used for user-authenticated sites. For instance, we will utilize this middleware on the user-profile page, which is only available to logged-in users. If the user isn’t logged in, this middleware will redirect them to the login page.

// auth.js

export default function auth({next,store}){

   let isLoggedIn = false // Can be calculated through store

   // let isLoggedIn = store.getters[‘sessionData/isLoggedIn’]

   if(!isLoggedIn){

    return next({

        name:’login’

    })

   }

   return next()

}

Configure multiple middlewares in router.js as shown below.

// router.js

import Vue from “vue”;

import VueRouter from “vue-router”;

import LoginPage from “@/pages/LoginPage.vue”

import UserProfile from “@/pages/UserProfile.vue”

import HelloWorld from “./components/HelloWorld”

import auth from “./middleware/auth”;

import middlewarePipeline from “./middleware/middleware-pipeline”;

import guest from “./middleware/guest”;

Vue.use(VueRouter)

const appRoutes = [

   {

    path: ‘/’,

    name: ‘home’,

    component: HelloWorld

   },

   {

    path: ‘/login’,

    name: ‘login’,

    component: LoginPage

   },

   {

    path: ‘/user-profile’,

    name: ‘user.profile’,

    meta: {

        middleware: [

            auth, guest

        ]

    },

    component: UserProfile

   }

]

const routes = […appRoutes]

const router = new VueRouter({

   mode: ‘history’,

   routes

})

router.beforeEach((to, from, next) => {

   /** Navigate to next if middleware is not applied */

   if (!to.meta.middleware) {

    return next()

   }

   const middleware = to.meta.middleware;

   const context = {

  to,

  from,

  next,

   //   store  | You can also pass store as an argument

   }

   return middleware[0]({

    …context,

    next:middlewarePipeline(context, middleware,1)

   })

 })

export default router

This middleware may be used to retrieve pertinent data. For example, with auth middleware, you may retrieve authentication data while ignoring guest users. It’s entirely up to you how you utilize it.

So, you are done with implementing the middleware pipeline in VueJS!

Conclusion

That concludes the lesson on how to build a middleware pipeline in VueJS. Middlewares are a wonderful approach to safeguard your application’s numerous paths. This was just a quick example of how to get started using middleware in VueJS.

 

0
Subhojit Hazra

Subhojit Hazra

He is a tech enthusiast and a passionate marketer with an eye for detail. He loves to uncomplicate things and debate on business problems. A quiet guy who likes peaceful evenings and iced coffees.

Add comment