{"id":17999,"library":"vue-route-middleware","title":"Vue Route Middleware","description":"`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.","status":"active","version":"1.0.7","language":"javascript","source_language":"en","source_url":"https://github.com/lionix-team/vue-route-middleware","tags":["javascript","vue","vuejs","router","routes","vue-router","middleware"],"install":[{"cmd":"npm install vue-route-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add vue-route-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add vue-route-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for router guard integration and defining routes with middleware meta.","package":"vue-router","optional":false},{"reason":"The library is built to integrate with Vue.js applications.","package":"vue","optional":false}],"imports":[{"note":"This is a default export. Ensure you are using the default import syntax for ESM. CommonJS `require` syntax is generally not used in modern Vue projects.","wrong":"import { VueRouteMiddleware } from 'vue-route-middleware';","symbol":"VueRouteMiddleware","correct":"import VueRouteMiddleware from 'vue-route-middleware';"},{"note":"When defining separate middleware files, they typically use default exports themselves, which are then imported into your router configuration.","symbol":"AuthMiddleware (example)","correct":"import AuthMiddleware from './path/to/authMiddleware';"}],"quickstart":{"code":"import Vue from 'vue';\nimport VueRouter from 'vue-router';\nimport VueRouteMiddleware from 'vue-route-middleware';\n\nVue.use(VueRouter);\n\n// Simulate user login status and payment status\nconst fakeUser = {\n  isLogged: () => localStorage.getItem('isLoggedIn') === 'true',\n  madePayment: () => localStorage.getItem('hasPaid') === 'true'\n};\n\n// Define dummy components\nconst Dashboard = { template: '<div><h1>Dashboard</h1><p>Welcome, {{ isLoggedIn ? \"User\" : \"Guest\" }}!</p></div>' };\nconst Login = { template: '<div><h1>Login Page</h1><p>Set isLoggedIn=true in localStorage to proceed.</p></div>' };\nconst Payment = { template: '<div><h1>Payment Page</h1><p>Set hasPaid=true in localStorage to proceed.</p></div>' };\nconst Home = { template: '<div><h1>Home Page</h1><p>Navigate to /dashboard.</p></div>' };\n\n// Define middleware functions\nconst AuthMiddleware = (to, from, next) => {\n  console.log('Running AuthMiddleware...');\n  if (!fakeUser.isLogged()) {\n    next({ name: 'Login' }); // Redirect to login\n    return false; // Crucial: stop middleware chain\n  }\n  next(); // Continue if authenticated\n};\n\nconst PaymentMiddleware = (to, from, next) => {\n  console.log('Running PaymentMiddleware...');\n  if (!fakeUser.madePayment()) {\n    next({ name: 'Payment' }); // Redirect to payment\n    return false; // Crucial: stop middleware chain\n  }\n  next(); // Continue if payment made\n};\n\nconst routes = [\n  { path: '/', name: 'Home', component: Home },\n  {\n    path: '/dashboard',\n    name: 'Dashboard',\n    component: Dashboard,\n    meta: {\n      middleware: ['AuthMiddleware', 'PaymentMiddleware'] // Apply named middlewares\n    }\n  },\n  { path: '/login', name: 'Login', component: Login },\n  { path: '/payment', name: 'Payment', component: Payment }\n];\n\nconst router = new VueRouter({\n  mode: 'history',\n  routes\n});\n\n// Initialize vue-route-middleware with named middlewares\nrouter.beforeEach(VueRouteMiddleware({ AuthMiddleware, PaymentMiddleware }));\n\n// Create and mount the Vue app (for a full runnable example)\n// new Vue({\n//   router,\n//   template: `\n//     <div id=\"app\">\n//       <router-link to=\"/\">Home</router-link> |\n//       <router-link to=\"/dashboard\">Dashboard</router-link> |\n//       <router-link to=\"/login\">Login</router-link> |\n//       <router-link to=\"/payment\">Payment</router-link>\n//       <hr>\n//       <router-view></router-view>\n//     </div>\n//   `\n// }).$mount('#app');\n\n// To test, open your browser console and set:\n// localStorage.setItem('isLoggedIn', 'true');\n// localStorage.setItem('hasPaid', 'true');\n// Then navigate to /dashboard.\n","lang":"javascript","description":"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`."},"warnings":[{"fix":"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.","message":"To halt the execution of subsequent middlewares in a chain, a middleware function must explicitly `return false`. If `false` is not returned, the chain will continue to execute, even if a redirect (`next({ name: '...' })`) has been triggered.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"Compatibility with Vue Router versions: This library is designed for Vue 2 and Vue Router 3. For Vue 3 applications, which use Vue Router 4, the router guard API has changed. Direct compatibility is not guaranteed, and you may need to adapt your middleware logic or consider alternatives built specifically for the Vue 3 ecosystem.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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()`.","message":"Middleware functions, especially those used with `beforeEach`, must always call `next()` (or `next(false)`, `next('/path')`, etc.) or explicitly `return false` if the chain should stop. Failure to do so will leave the navigation pending indefinitely, leading to a stuck user experience.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"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.","cause":"Multiple `next()` calls or conflicting redirects were triggered within the middleware chain without properly halting subsequent middleware execution.","error":"Navigation aborted with a different navigation. Or: Navigation failed because a redirect occurred."},{"fix":"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`.","cause":"The `VueRouteMiddleware()` function was not correctly invoked on a `vue-router` guard (e.g., `router.beforeEach`), or named middlewares were not passed to it when using the advanced object-based configuration.","error":"TypeError: Cannot read properties of undefined (reading 'meta') (or similar for missing middleware execution)"},{"fix":"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 }));`","cause":"You are attempting to use a named middleware in your route's `meta.middleware` array (e.g., `meta: { middleware: ['AuthMiddleware'] }`), but `AuthMiddleware` was not imported into your router file or not passed to the `VueRouteMiddleware` factory function.","error":"ReferenceError: [YourMiddlewareName] is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}