Skip to content

Instantly share code, notes, and snippets.

@nash403
Created February 13, 2025 15:44
Show Gist options
  • Save nash403/6e605b8f6cd19968d852d9e59c3fd658 to your computer and use it in GitHub Desktop.
Save nash403/6e605b8f6cd19968d852d9e59c3fd658 to your computer and use it in GitHub Desktop.
Basic Vue3 router middleware system
// auth middleware
import { useAuthStore } from "@/stores/auth";
export default async function auth({ next }) {
const authStore = useAuthStore();
const user = await authStore.checkAuth();
if (!( 'id' in user)) {
console.log("Not logged in");
return next({
name: "Login",
});
}
return next();
}
// hasCity middleware
import { useCitiesStore } from "@/stores/cities";
export default function hasCity({ next }) {
const citiesStore = useCitiesStore()
if (!citiesStore.city) {
console.log('City not selected')
return next({
name: 'CitySelector'
})
}
return next();
}
import auth from '@/middlewares/auth'
import hasCity from '@/middlewares/hasCity'
// other imports and code
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: {
middleware: [auth, hasCity]
}
},
{
path: '/login',
name: 'Login',
component: Login,
},
{
path: '/city-selector',
name: 'CitySelector',
component: CitySelector,
}
];
const router = createRouter({
routes,
});
function nextFactory(context, middlewares, index) {
const nextMiddleware = middlewares[index];
if (!nextMiddleware){
return context.next;
}
const subsequentMiddleware = nextFactory(context, middlewares, index + 1);
return nextMiddleware({ ...context, next: subsequentMiddleware })
}
router.beforeEach((to, from, next) => {
if(!to.meta.middleware){
return next();
}
const middlewares = Array.isArray(to.meta.middleware)
? to.meta.middleware
: [to.meta.middleware];
const context = {
to,
from,
next,
router,
};
return middlewares[0]({ ...context, next: nextFactory(context, middlewares, 1) });
});
export default router;
@nash403
Copy link
Author

nash403 commented Feb 13, 2025

existing fully-featured vue3 library implementation https://github.com/themustafaomar/vue-middleware

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment