Tutorial On How To Implement Middleware Pipeline In VueJS

Page 1

How to Implement Middleware Pipeline in VueJS? www.bacancytechnology.com


Introduction


A middleware is one of the most commonly used terms in web development that act as an intermediate between two applications or services. The powerful concept of middleware helps developers with routing and patterns related to it. In VueJS, middleware can be used for multiple layout switching, restricting some routes as per the user role, etc. This tutorial will discuss the steps to implement middleware pipeline in VueJS and further learn how you can use multiple middlewares on single routes. Let me list out some prerequisites for you.


Prerequisites : Implement Middleware Pipeline in VueJS


1. Basic knowledge about the working of VueJS 2. Familiarity with vue-router and navigation guards in Vue.js, And that’s it; we are good to go now

Create VueJS App With the help of the vue-cli tool, create a VueJS project.

Vue create vue-middleware-demo


You will be prompted to choose the Vue version, select vue-2

After selecting the relevant version, vuecli will install the dependencies, and now we can serve our project.

We have successfully created a new project,


Install vue-router Install vue-router using the below command. Here we will be using yarn to install vue-router; you can choose as per your convenience. If you are not familiar with vue-router, you can visit the Getting Started with Vue Router blog to explore more about it.

cd vue-middleware-demo yarn add vue-router Use the below command to serve the project.

yarn run serve


The initial default user interface will look something like this. Moving further in the tutorial, we will configure the routers in the next section.

Creating Routes In this section, we will set up some basic routes. Our demo application will have two web pages for Login and User’s profile. The structure will look like this.


../vue-middlewaredemo/src/pages/Login.vue ../vue-middlewaredemo/src/pages/UserProfile.vue

Create router.js file within src directory to configure routes for the demo application.

// 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

We are almost done with the configuration. Now, add router-view in App.vue to make them accessible.

// App.vue <template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <routerview></router-view> <!-Change: Add router view --> </div> </template> <script> export default { name: 'App', } </script>


UI for /login and UI for /user-profileRoute

Creating Middlewares Create our first middleware guest.js which will be responsible for navigating to the user-profile page only if the user is logged in.


// guest.js export default function guest({next,store}){ let isLoggedIn = false // Can be calculated through store if(isLoggedIn){ return next({ name: 'home' }) } return next(); } Now we need to create a middleware pipeline. The pipeline is responsible for communication between navigation guards and middlewares. Simply create a file named middleware-pipeline.js and use the below code snippet.


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


Once you are done with this file, configure it in router.js. We’ll use navigation guard and middleware-pipeline to execute middleware.

// 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 }) }) The connection is established now. The next step is to configure the middleware in the required path, for now we will implement guest middleware in /login which means if the user is logged in (hard coded for now) then it redirects the user from Login page to Home page. So let’s add this middleware to our routes. Use the following object where you want to apply the middleware. Remember: You need to import guest middleware then only you will be able to configure it


{ path: '/login', name: 'login', meta: { middleware: [ guest ] }, component: LoginPage }, After all these changes to router.js this is how your file should look like

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 middlewarePipeline 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


Navigate to http://localhost:8080/login you will notice that you are being redirected to Home Page or http://localhost:8080/ route. Congratulations! You have successfully implemented a middleware pipeline in Vue.js. Now, it’s time to add multiple middlewares to the same routes.

Configure Multiple Middlewares Hoping that you remember that we have added some extra metadata to the Login route. This is how the path object should look like.


{ path: '/login', name: 'login', meta: { middleware: [ guest ] }, component: LoginPage }, Notice the middleware key here. A middleware key is a type of array which means that we can pass multiple middleware to this key. So, let’s create one more middleware with the name auth.js which we will use for user authenticated pages. For example, we will apply this middleware to /user-profile page and this page is only accessible to logged-in users. If the user is not logged in then this middleware will push the user 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() }

Now in router.js you can configure multiple middleware 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


} return middleware[0]({ ...context, next:middlewarePipeline(context, middleware,1) }) }) export default router


Note: Here auth and guest both these middleware are contradictory to each other so in this example we will see how we can configure multiple middleware. You can utilize this middleware to fetch relevant data. For example, you can fetch auth related data in auth middleware and can ignore guest users. It’s all up to you how you want to use it. So, that’s it we are done implementing the middleware pipeline in VueJS!


Github Repository: Middleware Pipeline Example


Feel free to visit the source code and clone the repository using the below command.

git clone https://github.com/iamsantoshyadav/vuemiddleware-demo.git


Conclusion That’s it for the tutorial on how to implement a middleware pipeline in VueJS. Middlewares are an excellent way to protect various routes of your application. This was just a simple demonstration of how you can get started with middleware in VueJS. Please write to us back with any suggestions or feedback. You can also visit Vuejs tutorials page where you can find similar topics with the GitHub repository to play around with the code.


Thank You

www.bacancytechnology.com


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.