`vue-route-middleware` is a lightweight utility for Vue.js applications designed to streamline and enhance the management of route middleware logic within `vue-router`. It simplifies the definition and execution of complex global route guards, offering both inline function and chainable middleware arrays directly within route meta fields. The library is currently stable at version 1.0.7, with its last major release (v1.0.0) providing the core functionality, followed by minor updates. Its primary differentiator is the ability to define middleware either as direct functions, an array of functions for chaining, or as named functions referenced from an object passed to `VueRouteMiddleware()`, allowing for flexible application across different router guards like `beforeEach` and `afterEach`. It promotes clean, readable route configurations by abstracting complex guard logic, making it easier to manage permissions, tracking, and other route-specific concerns. It does not introduce breaking changes frequently, focusing on stability within the 1.x series.
npm install vue-route-middlewareVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate and use `vue-route-middleware` with `vue-router` in a basic Vue 2 application. It shows defining and chaining named middleware functions to protect a '/dashboard' route based on simulated authentication and payment status, applying them via `router.beforeEach`.
After calling `next()` for a redirect or error, add `return false;` at the end of your middleware function to prevent further middlewares in the array from running.
Ensure your project is using Vue 2 and Vue Router 3. If migrating to Vue 3, carefully review the `vue-router` 4 documentation for `beforeEach` and `afterEach` guard changes, or seek a Vue 3 native middleware solution.
Always include `next()` at the end of your middleware function's successful path, and ensure `return false` is used when a redirect or halt is initiated via `next()`.
Ensure that if a middleware performs a redirect (e.g., `next({ name: 'Login' })`), it immediately `return false;` to prevent other middlewares in the chain from executing and potentially causing further navigation actions.Verify that `router.beforeEach(VueRouteMiddleware());` or `router.beforeEach(VueRouteMiddleware({ AuthMiddleware, PaymentMiddleware }));` is present in your router setup, and that all named middlewares referenced in `meta.middleware` are included in the object passed to `VueRouteMiddleware`.Import `AuthMiddleware` from its respective file (e.g., `import AuthMiddleware from './route/middleware/auth';`) and then include it in the object passed to the `VueRouteMiddleware` initializer: `router.beforeEach(VueRouteMiddleware({ AuthMiddleware }));`