SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Ähnlich wie How to Implement Middleware Pipeline in VueJS.pdf

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

Ähnlich wie How to Implement Middleware Pipeline in VueJS.pdf (20)

Vue JS @ MindDoc. The progressive road to online therapy
Vue JS @ MindDoc. The progressive road to online therapyVue JS @ MindDoc. The progressive road to online therapy
Vue JS @ MindDoc. The progressive road to online therapy
 
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
 
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!
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Vue.js part1
Vue.js part1Vue.js part1
Vue.js part1
 
ngNewRouter
ngNewRouterngNewRouter
ngNewRouter
 
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
 
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
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
 
Vue business first
Vue business firstVue business first
Vue business first
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
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
 
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
 
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
 
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
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 

Mehr von Katy Slemon

Mehr von 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
 
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
 
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
 
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
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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.