- Injecting custom object for middlewares
- Adjusting multiple middleware rules
- Easy implementation
$ npm i @grafikri/vue-middleware
You can also inject any object to a module to take it in middleware method(recommended vuex store, it will be mentioned below)
// main.js
import router from "./router"
import middleware from "@grafikri/vue-middleware"
router.beforeEach(middleware())
You can put your middleware methods under any folder. There is no rule for this.
// middleware/authentication.js
export default ({ to, from, next }) => {
// Your custom if statement
if (!userLoggedIn) {
next("/login")
return false
}
next()
}
Mentioned params
to
,from
, andnext
completely same with Vue Router navigation guard params
// router/index.js
import authentication from "../middleware/authentication"
const routes = [
{
path: "/user-profile",
meta: {
middleware: [authentication],
},
},
]
You can inject any object
// main.js
import router from "./router"
import store from "./store"
import middleware from "@grafikri/vue-middleware"
router.beforeEach(middleware({ store }))
to retrive it inside of middleware method
// middleware/authentication.js
export default ({ store, next }) => {
if (!store.state.user.loggedIn) {
next("/login")
return false
}
next()
}
There is one important rule for chaining that you must return
false
if you want to stop the next middleware method.
You can define more than one middleware methods that will be invoked respectively.
// router/index.js
import authentication from "../middleware/authentication"
import authorization from "../middleware/authorization"
const routes = [
{
path: "/payments",
meta: {
middleware: [authentication, authorization],
},
},
]