Vue Middleware Plugin
raw JSON →vue-middleware is a Vue.js plugin designed to simplify the creation and management of custom middleware, particularly for handling roles and permissions within Vue applications. It draws inspiration from Nuxt's middleware system but extends functionality to include robust role and permission management through a driver-based approach, which is highlighted for its ease of integration with backend frameworks like Laravel. The current version, 1.0.0-alpha.7, indicates it is still in active development, suggesting potential API changes before a stable release. It aims to provide a zero-configuration experience for common backend integrations, making it easier to guard routes based on user roles and permissions. Vue.js itself does not have a fixed release cycle; patch releases are made as needed, and minor releases with new features typically occur every 3-6 months.
Common errors
error Error: "vueMiddleware" is not a function ↓
import { vueMiddleware } from 'vue-middleware'. error Property 'middleware' does not exist on type 'RouteMeta' ↓
RouteMeta interface in a .d.ts file or directly in a global type declaration. For example:
declare module 'vue-router' {
interface RouteMeta {
middleware?: string | string[];
}
} error npm WARN vue-middleware@1.0.0-alpha.7 requires a peer of vue@^3.0.0 but none is installed. ↓
npm install vue@^3.0.0 or yarn add vue@^3.0.0. Ensure your project's Vue version is compatible with the vue-middleware's peer dependency requirement. Warnings
breaking As an alpha release (1.0.0-alpha.7), the API for `vue-middleware` is subject to change. Breaking changes are highly likely in future minor or major releases before a stable `1.0.0` version. ↓
gotcha Ensure `vue-router` is correctly installed and used (`app.use(router)`) *before* `vue-middleware` (`app.use(vueMiddleware)`) in your application setup. `vue-middleware` relies on `vue-router`'s navigation guards and route metadata. ↓
gotcha When defining middleware, carefully manage the `redirect`, `abort`, and `guard` functions provided in the `MiddlewareContext`. Incorrect usage can lead to infinite redirect loops, blocked navigation, or unexpected route transitions. ↓
Install
npm install vue-middleware yarn add vue-middleware pnpm add vue-middleware Imports
- vueMiddleware wrong
const vueMiddleware = require('vue-middleware')correctimport { vueMiddleware } from 'vue-middleware' - MiddlewareContext wrong
import type { MiddlewareContext } from 'vue-middleware'correctimport { MiddlewareContext } from 'vue-middleware' - App wrong
import App from 'vue'correctimport { createApp, App } from 'vue'
Quickstart
import { createApp, App } from 'vue';
import { vueMiddleware, MiddlewareContext } from 'vue-middleware';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
// Assume these components exist for demonstration
const AppRoot = { template: '<div><router-view></router-view></div>' };
const DashboardLayout = { template: '<div>Dashboard Layout <router-view></router-view></div>' };
const DashboardHomePage = { template: '<div>Dashboard Home</div>' };
const DashboardUsersPage = { template: '<div>Dashboard Users</div>' };
const routes: Array<RouteRecordRaw> = [
{
name: 'dashboard',
path: '/dashboard',
component: DashboardLayout,
meta: {
middleware: 'dashboard', // This dashboard and its children are now guarded using the dashboard middleware
},
children: [
{
name: 'dashboard_home',
path: '',
component: DashboardHomePage,
},
{
name: 'dashboard_users',
path: 'users',
component: DashboardUsersPage,
},
]
},
{
path: '/',
redirect: '/dashboard'
}
];
const router = createRouter({
history: createWebHistory(),
routes,
});
const app: App = createApp(AppRoot);
app.use(router); // Vue Router must be installed before vue-middleware
app.use(vueMiddleware, {
middleware: {
dashboard: ({ app, router, from, to, redirect, abort, guard }: MiddlewareContext) => {
console.log('Dashboard middleware triggered for:', to.path);
// Example: Simulate an authentication check
const isAuthenticated = true; // Replace with actual auth logic (e.g., check token, user role)
if (!isAuthenticated) {
console.log('User not authenticated, redirecting...');
redirect('/login'); // Assuming a login route exists
}
// If authenticated, allow navigation
// No explicit `next()` needed as vue-middleware handles the flow if no redirect/abort is called
},
},
});
app.mount('#app');
console.log('App mounted. Try navigating to /dashboard or /dashboard/users');