Skip to content

Instantly share code, notes, and snippets.

@mbougarne
Created February 8, 2020 21:42
Show Gist options
  • Select an option

  • Save mbougarne/35931e9dcf40d5a2142116ac90a54aa4 to your computer and use it in GitHub Desktop.

Select an option

Save mbougarne/35931e9dcf40d5a2142116ac90a54aa4 to your computer and use it in GitHub Desktop.
Sample middleware for Vue Router.

We'll try to create and use middlewares for Vue Router in diffetent way, we'll start with the simpliest then dive deeper!

01 - Navigation Guards

Read More about here, It give us 3 option to work with routes, beforeEnter/beforeLeave/beforeRouteUpdate it's check request before accessing the route then you can decide what to do with it, but you can't triget what's going there in beforeEnter/Leave, you can watch the $route in watch method or in beforeRouteUpdatem a simple example is like this:

const router = new VueRouter({
  mode: 'history',
  routes: [
    { 
    	path: '/dashboard', 
    	component: VueComponent, 
    	beforeEnter: (to, from, next) => {
      	# to: the route that we want to access to
        # from: this route! The route that we're in currently
        # next(): Resolve the route
        # Here you can do some checking such as if the user is auth or have permission..
        if(!isAuth) next({name: 'loginRoute'})
        # example two
        if(!isAdmin) next({path: 'notFound'})
        #example Three
        if(!hasPermission) next(error)
        next()
      }
    },
  ]
})

02 - Global Before Guards

You can check before accessing to desired route or after, like so:

# This will work before accessing to each route
router.beforeEach((to, from, next) => {
  next()
})
# This will work after accessing to each route
router.afterEach((to, from) => {
  console.log('afterEach')
})

03 - Ad a module

You can create a folder called middlewares then inside that you can start add middleware file, like so:

  • auth.js
  • guest.js
  • log.js This is a sample example of adding a middleware as a module, let's take this path middlewares/auth.js:
export default guestMiddleware = (to, from, next) => {
    if(!isAuth) return next({ name: 'loginRoute'})
    return next({path: '/dashboard'})
 }

In your routes.js

import guestMiddleware from '/path/to/middlewares/auth.js'

guestMiddleware

const router = new Router({
    routes: [{
            path: '/dashboard',
            name: 'dashboardRoute',
            component: DashboardComponent,
            meta: {
                title: 'The HTML Title tage: welcome to dashboard',
                metaTags: [
                  {
                    name: 'description',
                    content: 'some description here.'
                  }
                ]
                middleware: [
                    guestMiddleware # You can add many middelwares
                ]
            }
        },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment