@yazida/vue-router-middleware
is a lightweight and flexible middleware system for Vue Router in Vue 3 applications. It allows you to define global or inline middleware for route navigation, enabling advanced use cases such as authentication, logging, or other route-specific logic.
Install the package via npm:
# PNPM
pnpm add @yazida/vue-router-middleware
# YARN
yarn add @yazida/vue-router-middleware
# NPM
npm install @yazida/vue-router-middleware
- Global Middleware Registration: Register middleware globally by name for reuse.
- Inline Middleware Support: Use middleware directly in route definitions.
- Flexible Pipeline: Chain multiple middleware functions for a single route.
- TypeScript Support: Fully typed for robust development.
You can register middleware globally for reuse across your application:
import { registerMiddleware } from '@yazida/vue-router-middleware';
// Example: Authentication middleware
registerMiddleware('auth', ({ to, next }) => {
if (!isAuthenticated() && to.meta.requiresAuth) {
return next('/login');
}
next();
});
// Example: Logging middleware
registerMiddleware('log', ({ to, from }) => {
console.log(`Navigating from ${from.fullPath} to ${to.fullPath}`);
});
Add middleware to your routes using the meta.middleware
property:
import { createRouter, createWebHistory } from 'vue-router';
import { createVueRouterMiddleware } from '@yazida/vue-router-middleware';
const routes = [
{
path: '/',
component: Home,
meta: { middleware: ['auth', 'log'] },
},
{
path: '/about',
component: About,
meta: { middleware: 'log' },
},
{
path: '/login',
component: Login,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Initialize middleware handling
createVueRouterMiddleware(router);
export default router;
Define middleware directly in route definitions:
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: {
middleware: ({ to, next }) => {
if (!hasAccess(to.params.id)) {
return next('/403');
}
next();
},
},
},
];
Registers a middleware function globally under the specified name.
name
: A unique identifier for the middleware.middleware
: The middleware function.
registerMiddleware('example', ({ to, next }) => {
console.log(`Navigating to: ${to.fullPath}`);
next();
});
Enhances the Vue Router instance to process middleware during navigation.
router
: The Vue Router instance to enhance.
createVueRouterMiddleware(router);
registerMiddleware('auth', ({ to, next }) => {
if (!isAuthenticated() && to.meta.requiresAuth) {
return next('/login');
}
next();
});
registerMiddleware('log', ({ to, from }) => {
console.log(`Navigating from ${from.fullPath} to ${to.fullPath}`);
});
Contributions are welcome! To contribute:
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Submit a pull request with a clear description of your changes.
This project is licensed under the MIT License. See the LICENSE file for details.
Special thanks to the Yazida team for the support.