How to Implement Middleware Pipeline in VueJS.pdf

Katy Slemon
Katy SlemonSr. Tech Consultant at Bacancy Technology à Bacancy Technology

Checkout this step-by-step tutorial to implement middleware pipeline in VueJS and learn how you can use multiple middlewares on single routes.

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

Recommandé

How to Build SPA with Vue Router 2.0 par
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0Takuya Tejima
18.5K vues22 diapositives
Love at first Vue par
Love at first VueLove at first Vue
Love at first VueDalibor Gogic
660 vues37 diapositives
An introduction to Vue.js par
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
440 vues127 diapositives
Angular routing par
Angular routingAngular routing
Angular routingSultan Ahmed
218 vues33 diapositives
Vuejs for Angular developers par
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developersMikhail Kuznetcov
5.7K vues37 diapositives
Angular2RoutingSetupByShubham par
Angular2RoutingSetupByShubhamAngular2RoutingSetupByShubham
Angular2RoutingSetupByShubhamShubham Verma
184 vues3 diapositives

Contenu connexe

Similaire à How to Implement Middleware Pipeline in VueJS.pdf

Vue JS @ MindDoc. The progressive road to online therapy par
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 therapyDarío Blanco Iturriaga
183 vues34 diapositives
Introducing Rendr: Run your Backbone.js apps on the client and server par
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 serverSpike Brehm
39.7K vues82 diapositives
8 things you didn't know about the Angular Router, you won't believe #6! par
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
580 vues49 diapositives
App development with quasar (pdf) par
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)wonyong hwang
999 vues92 diapositives
Routing And Navigation par
Routing And NavigationRouting And Navigation
Routing And NavigationEyal Vardi
607 vues24 diapositives
Reactive application using meteor par
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
278 vues106 diapositives

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

Introducing Rendr: Run your Backbone.js apps on the client and server par Spike Brehm
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 Brehm39.7K vues
8 things you didn't know about the Angular Router, you won't believe #6! par Laurent Duveau
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 Duveau580 vues
App development with quasar (pdf) par wonyong hwang
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
wonyong hwang999 vues
Routing And Navigation par Eyal Vardi
Routing And NavigationRouting And Navigation
Routing And Navigation
Eyal Vardi607 vues
Reactive application using meteor par Sapna Upreti
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti278 vues
Angular js routing options par Nir Kaufman
Angular js routing optionsAngular js routing options
Angular js routing options
Nir Kaufman14.9K vues
ngNewRouter par phidong
ngNewRouterngNewRouter
ngNewRouter
phidong3.4K vues
How to build crud application using vue js, graphql, and hasura par Katy Slemon
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 Slemon143 vues
How to Build ToDo App with Vue 3 + TypeScript par Katy Slemon
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 Slemon407 vues
Angular 2.0 Routing and Navigation par Eyal Vardi
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
Eyal Vardi2.5K vues
Django + Vue, JavaScript de 3ª generación para modernizar Django par Javier Abadía
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ía4.6K vues
Front end development with Angular JS par Bipin
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
Bipin861 vues

Plus de Katy Slemon

Data Science Use Cases in Retail & Healthcare Industries.pdf par
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.pdfKaty Slemon
117 vues37 diapositives
How Much Does It Cost To Hire Golang Developer.pdf par
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.pdfKaty Slemon
78 vues31 diapositives
What’s New in Flutter 3.pdf par
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
85 vues24 diapositives
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf par
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.pdfKaty Slemon
72 vues36 diapositives
How to Build Laravel Package Using Composer.pdf par
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
68 vues32 diapositives
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf par
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.pdfKaty Slemon
53 vues19 diapositives

Plus de Katy Slemon(20)

Data Science Use Cases in Retail & Healthcare Industries.pdf par Katy Slemon
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 Slemon117 vues
How Much Does It Cost To Hire Golang Developer.pdf par Katy Slemon
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 Slemon78 vues
What’s New in Flutter 3.pdf par Katy Slemon
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon85 vues
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf par Katy Slemon
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 Slemon72 vues
How to Build Laravel Package Using Composer.pdf par Katy Slemon
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon68 vues
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf par Katy Slemon
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 Slemon53 vues
How to Develop Slack Bot Using Golang.pdf par Katy Slemon
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon75 vues
IoT Based Battery Management System in Electric Vehicles.pdf par Katy Slemon
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 Slemon930 vues
Understanding Flexbox Layout in React Native.pdf par Katy Slemon
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon128 vues
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf par Katy Slemon
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 Slemon178 vues
New Features in iOS 15 and Swift 5.5.pdf par Katy Slemon
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 Slemon114 vues
Choose the Right Battery Management System for Lithium Ion Batteries.pdf par Katy Slemon
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 Slemon117 vues
Angular Universal How to Build Angular SEO Friendly App.pdf par Katy Slemon
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 Slemon110 vues
Ruby On Rails Performance Tuning Guide.pdf par Katy Slemon
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon122 vues
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf par Katy Slemon
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 Slemon39 vues
Unit Testing Using Mockito in Android (1).pdf par Katy Slemon
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon114 vues
Why Use React Js A Complete Guide (1).pdf par Katy Slemon
Why Use React Js A Complete Guide (1).pdfWhy Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdf
Katy Slemon161 vues
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf par Katy Slemon
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdfWhy Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Katy Slemon535 vues
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf par Katy Slemon
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdfBacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Katy Slemon71 vues
How to Integrate Google Adwords API in Laravel App.pdf par Katy Slemon
How to Integrate Google Adwords API in Laravel App.pdfHow to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdf
Katy Slemon426 vues

Dernier

Combining Orchestration and Choreography for a Clean Architecture par
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean ArchitectureThomasHeinrichs1
69 vues24 diapositives
RADIUS-Omnichannel Interaction System par
RADIUS-Omnichannel Interaction SystemRADIUS-Omnichannel Interaction System
RADIUS-Omnichannel Interaction SystemRADIUS
15 vues21 diapositives
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... par
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...Vadym Kazulkin
75 vues64 diapositives
Igniting Next Level Productivity with AI-Infused Data Integration Workflows par
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Safe Software
225 vues86 diapositives
Spesifikasi Lengkap ASUS Vivobook Go 14 par
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14Dot Semarang
35 vues1 diapositive
Data-centric AI and the convergence of data and model engineering: opportunit... par
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...Paolo Missier
34 vues40 diapositives

Dernier(20)

Combining Orchestration and Choreography for a Clean Architecture par ThomasHeinrichs1
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean Architecture
RADIUS-Omnichannel Interaction System par RADIUS
RADIUS-Omnichannel Interaction SystemRADIUS-Omnichannel Interaction System
RADIUS-Omnichannel Interaction System
RADIUS15 vues
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... par Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin75 vues
Igniting Next Level Productivity with AI-Infused Data Integration Workflows par Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software225 vues
Spesifikasi Lengkap ASUS Vivobook Go 14 par Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 vues
Data-centric AI and the convergence of data and model engineering: opportunit... par Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier34 vues
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen... par NUS-ISS
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
NUS-ISS28 vues
Future of Learning - Yap Aye Wee.pdf par NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS41 vues
Business Analyst Series 2023 - Week 3 Session 5 par DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10209 vues
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors par sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab15 vues
Understanding GenAI/LLM and What is Google Offering - Felix Goh par NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS41 vues
Web Dev - 1 PPT.pdf par gdsczhcet
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet55 vues
Empathic Computing: Delivering the Potential of the Metaverse par Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
How the World's Leading Independent Automotive Distributor is Reinventing Its... par NUS-ISS
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...
NUS-ISS15 vues
AI: mind, matter, meaning, metaphors, being, becoming, life values par Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... par NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS34 vues

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.