New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
docs: setting middleware at build time #23480
Conversation
Instead of using 'definePageMeta' on each page, it may be handy to just on certain routes that should have a certain middle ware
Run & review this pull request in StackBlitz Codeflow. |
β Live Preview ready!
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure I would recommend this as it will only run on the first load and not on subsequent navigations.
You could however add the named middleware in ~/app/router.options.ts
or even at build time in pages:extend
hook, which would probably be the most performant option.
I tried it and you are correct. could you please show how to do this from the pages:extend hook |
import type { NuxtPage } from 'nuxt/schema'
export default defineNuxtConfig({
hooks: {
'pages:extend' (pages) {
function setMiddleware (pages: NuxtPage[]) {
for (const page of pages) {
if (/* some condition */ true) {
page.meta ||= {}
// Note that this will override any middleware set in `definePageMeta` in the page
page.meta.middleware = ['named']
}
if (page.children) {
setMiddleware(page.children)
}
}
}
setMiddleware(pages)
}
}
}) |
Apply to route groups using page:extend hook
Thank you for your help Dan. While I was waiting for your answer yesterday, I went experimenting and discovered that i could achieve the same thing by creating a global middleware and calling other middleware like this: import auth from "~/middleware/auth";
import admin from "~/middleware/admin";
export default defineNuxtRouteMiddleware((to, from) => {
const currentRoute = to.fullPath;
if (currentRoute.includes("/dashboard")) {
//The check for admin group should come first, else /dashboard will run and return
//Then routes like /dashboard/admin will pass
if (currentRoute.includes("/admin")) {
return admin(to, from);
}
return auth(to, from);
}
}); What do you think about this? |
Instead of using 'definePageMeta' on each page, it may be handy to just on certain routes that should have a certain middle ware
π Linked issue
β Type of change
π Description
π Checklist