SlideShare a Scribd company logo
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, vue-
cli 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-middleware-
demo/src/pages/Login.vue
../vue-middleware-
demo/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"> <router-
view></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/vue-
middleware-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

More Related Content

Similar to How to Implement Middleware Pipeline in VueJS.pdf (20)

Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
Vue JS Interview Questions By Scholarhat
Vue JS Interview Questions By ScholarhatVue JS Interview Questions By Scholarhat
Vue JS Interview Questions By Scholarhat
Scholarhat
 
8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!
Laurent Duveau
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
wonyong hwang
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
Eyal Vardi
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
Nir Kaufman
 
Vue.js part1
Vue.js part1Vue.js part1
Vue.js part1
욱래 김
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouter
phidong
 
How to build crud application using vue js, graphql, and hasura
How to build crud application using vue js, graphql, and hasuraHow to build crud application using vue js, graphql, and hasura
How to build crud application using vue js, graphql, and hasura
Katy Slemon
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
Yoram Kornatzky
 
Vue business first
Vue business firstVue business first
Vue business first
Vitalii Ratyshnyi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
Eyal Vardi
 
import React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdfimport React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdf
stopgolook
 
reactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdfreactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdf
sunilkhetpal
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptx
BOSC Tech Labs
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
Visual Engineering
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
TO THE NEW Pvt. Ltd.
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
Vue JS Interview Questions By Scholarhat
Vue JS Interview Questions By ScholarhatVue JS Interview Questions By Scholarhat
Vue JS Interview Questions By Scholarhat
Scholarhat
 
8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!8 things you didn't know about the Angular Router, you won't believe #6!
8 things you didn't know about the Angular Router, you won't believe #6!
Laurent Duveau
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
wonyong hwang
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
Eyal Vardi
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
Nir Kaufman
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouter
phidong
 
How to build crud application using vue js, graphql, and hasura
How to build crud application using vue js, graphql, and hasuraHow to build crud application using vue js, graphql, and hasura
How to build crud application using vue js, graphql, and hasura
Katy Slemon
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
Eyal Vardi
 
import React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdfimport React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdf
stopgolook
 
reactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdfreactmuiquestion For some reason getting the following error fr.pdf
reactmuiquestion For some reason getting the following error fr.pdf
sunilkhetpal
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptx
BOSC Tech Labs
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
Visual Engineering
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptxFIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptxFIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Ad

How to Implement Middleware Pipeline in VueJS.pdf

  • 3. 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.
  • 5. 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
  • 6. You will be prompted to choose the Vue version, select vue-2 After selecting the relevant version, vue- cli will install the dependencies, and now we can serve our project. We have successfully created a new project,
  • 7. 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
  • 8. 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.
  • 9. ../vue-middleware- demo/src/pages/Login.vue ../vue-middleware- demo/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)
  • 10. 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({
  • 11. 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"> <router- view></router-view> <!-- Change: Add router view --> </div> </template> <script> export default { name: 'App', } </script>
  • 12. 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.
  • 13. // 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.
  • 14. 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
  • 15. 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 }
  • 16. 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
  • 17. { 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"
  • 18. 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
  • 19. }, 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()
  • 20. 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
  • 21. 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.
  • 22. { 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.
  • 23. // 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.
  • 24. // 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 = [ {
  • 25. path: '/', name: 'home', component: HelloWorld }, { path: '/login', name: 'login', component: LoginPage }, { path: '/user-profile', name: 'user.profile', meta: { middleware: [ auth, guest ] }, component: UserProfile } ]
  • 26. 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
  • 28. 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!
  • 30. Feel free to visit the source code and clone the repository using the below command. git clone https://github.com/iamsantoshyadav/vue- middleware-demo.git
  • 31. 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.