Vue Middleware Plugin

raw JSON →
1.0.0-alpha.7 verified Thu Apr 23 auth: no javascript

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.

error Error: "vueMiddleware" is not a function
cause Attempting to use `vueMiddleware` as a default import or without destructuring when it's a named export.
fix
Ensure you are using a named import: import { vueMiddleware } from 'vue-middleware'.
error Property 'middleware' does not exist on type 'RouteMeta'
cause TypeScript compiler error indicating that the `meta` property of a Vue Router `RouteRecordRaw` does not recognize the custom `middleware` key. This is common when extending router types.
fix
You need to augment the 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.
cause This warning occurs because `vue-middleware` declares `vue` as a peer dependency, meaning your project is expected to provide it, but it's either missing or the version doesn't match the required range.
fix
Install the required version of Vue in your project: 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.
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.
fix Refer to the official documentation and migration guides for each new release. Pinning exact versions (`~` or `^`) is not recommended for alpha software in production.
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.
fix Always register `vue-router` first: `app.use(router); app.use(vueMiddleware, ...);`
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.
fix Test middleware logic thoroughly, especially with conditional redirects. Ensure that a path is always reachable or that `abort()` is called appropriately. Review `vue-middleware` documentation for detailed examples of middleware flow control.
npm install vue-middleware
yarn add vue-middleware
pnpm add vue-middleware

This quickstart demonstrates how to install `vue-middleware`, register a global 'dashboard' middleware, and apply it to specific routes in a Vue 3 application using Vue Router. It shows the basic setup and how the middleware context can be used for conditional navigation (e.g., authentication checks).

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');