Skip to content

Instantly share code, notes, and snippets.

@acfatah
Last active March 27, 2024 04:40
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save acfatah/719c67a4effb63d4ebe053ab00561093 to your computer and use it in GitHub Desktop.
Save acfatah/719c67a4effb63d4ebe053ab00561093 to your computer and use it in GitHub Desktop.
Quasar Vue Router Middleware Pipeline Example
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import middlewarePipeline from './middleware-pipeline'
Vue.use(VueRouter)
/*
* If not building with SSR mode, you can
* directly export the Router instantiation
*/
export default function (/* { store, ssrContext } */ { store }) {
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
// Leave these as is and change from quasar.conf.js instead!
// quasar.conf.js -> build -> vueRouterMode
// quasar.conf.js -> build -> publicPath
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE
})
/**
* Run the middleware(s) using the beforeEach hook
*/
Router.beforeEach((to, from, next) => {
if (!to.meta.middlewares) return next()
let middlewares = to.meta.middlewares
let context = { to, from, next, store }
return middlewares[0]({
...context,
next: middlewarePipeline(context, middlewares, 1)
})
})
return Router
}
// router/middleware-pipeline.js
/**
* A stack of different middlewares ran in series
* Link: https://blog.logrocket.com/vue-middleware-pipelines/
*/
function middlewarePipeline (context, middlewares, index) {
let middleware = middlewares[index]
if (!middleware) return context.next
return () => {
let nextMiddleware = middlewarePipeline(
context, middlewares, index + 1
)
middleware({ ...context, next: nextMiddleware })
}
}
export default middlewarePipeline
// router/middlewares.js
/**
* Auth middleware example.
*/
export function auth (/* { to, from, next, store } */ { next, store }) {
if(!store.getters.auth) {
return next({ name: 'login' })
}
return next()
}
// router/routes.js
import auth from './middlewares'
const routes = [
// ...
{
path: '/login',
name: 'login',
component: Login
},
// An example of route using auth middleware
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
middlewares: [ auth ]
},
}
// ...
]
export default routes
@drmicobo
Copy link

drmicobo commented Mar 9, 2021

wow this is helpful

@aminhd2658
Copy link

I have error:
TypeError: Cannot read properties of undefined (reading 'getters')
From [middlewares.js] in line 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment