Skip to content

Instantly share code, notes, and snippets.

@juanrdlo
Forked from acfatah/index.js
Created March 27, 2024 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanrdlo/d6c1cc227eddd9f6b20829433b1eafba to your computer and use it in GitHub Desktop.
Save juanrdlo/d6c1cc227eddd9f6b20829433b1eafba 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment