You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
CASE 1: This means that if you want to execute middleware only for specific routes, you need to include a condition that checks the path:
exportdefaultdefineEventHandler(async(event)=>{//I'm not sure about the props names, it's just to show an example hereif(event.path=="/api/user/hello")&&event.context.user.role!='USER'&&event.method!="GET")return;console.log("User role allowed");});
However, this approach is not ideal as it conflicts with the auto-generation process and naming conventions of Nuxt's server/api folder. If a file is moved to a different folder and the middleware condition isn't updated accordingly, it can lead to application-breaking issues.
Luckily there is a more elegant way to do it, you can use the h3onRequest prop on your handler (see nuxt/nuxt#23308 (reply in thread)).
exportdefaultdefineEventHandler({onRequest: [// Allow only specific environnement(event)=>blockWrongEnv(event,["DEV","TEST"]),// Retrieve redis sessionuseSession,// Check if the role of the user is correct(event)=>apiRouteRoleCheck(event,["RECEPTION"]),// Check 2FA code2faCheck,],///[...]
But this syntax brings other issues when your project starts to grow:
Your server/api folder can become cluttered with numerous routes, making it challenging to review the onRequest middleware list in each file.
Adding a new route often involves copying and pasting from an existing route, which increases the likelihood of forgetting to update the onRequest middleware property.
There are no safeguards to verify that all routes are properly secured with the apiRouteAdminCheck middleware or any other required middleware.
Feature request:
The h3onRequest syntax would be beneficial to define a list of paths, sub-paths, methods, or files that must be validated during build or startup to ensure they include a specified set of middleware.
Current workaround:
I'm using a pre-commit Git hook to run a script that applies regex tests to ensure the presence of the required middleware.
Inspiration?:
Here's an example of how I reimplemented an inspired Nuxt server/api route auto-generation mechanism and h3onRequest logic in another project based on Fastify. The startup script for loading the routes also incorporates some of the checks mentioned earlier:
constbaseRoute=match?.[1]?.replaceAll("\\","/")??"";constisAdminRoute=baseRoute.startsWith("/admin");constisWebhookRoute=baseRoute.startsWith("/webhooks");constmethod=match[4]as"post"|"get"|"delete"|"head"|"patch"|"put"|"options";constsubRoute=match[5];constfullRoute=baseRoute+(subRoute=="index" ? "" : `/${subRoute}`);constmiddlewares=(routeObj?.opt?.preHandlerasany[])??[];consthasMiddlewares=middlewares.length>0;//Admin routes are decorated with middlewareIsAdminif(isAdminRoute&&(!hasMiddlewares||(hasMiddlewares&&!middlewares.includes(middlewareIsAdminConnected)))){logger.error(`Admin route not decorated with middlewareIsAdminConnected: ${routeFile}`);process.exit(1);}//PATCH/PUT/POST/DELETE routes are decorated with middlewareCSRF (and in first position)if(!isWebhookRoute&&["post","patch","put","delete"].indexOf(method)!=-1&&(!hasMiddlewares||(hasMiddlewares&&middlewares.indexOf(middlewareCSRF)!=0))){logger.error(`POST/PATCH/PUT/DELETE route not decorated with middlewareCSRF (or not placed on first position): ${routeFile}`);process.exit(1);}
In this case, the server would fail to start if the routes were not properly decorated, preventing the exposure of admin routes or no CSRF protection.
Representing the feature:
Let's say, you want to assure on startup or on build that :
all routes "POST" has the CSRF middleware
all routes under /server/api/user and /server/api/admin has a isConnected middleware
all routes under /server/api/user has a roleCheck middleware
all routes under /server/api/admin has a adminOnly middleware
all routes "POST" under /server/api/2FA has a twoFa middleware
This discussion was converted from issue #2934 on December 13, 2024 10:37.
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Describe the feature
Describe the feature
Nuxt server middleware will:
CASE 1: This means that if you want to execute middleware only for specific routes, you need to include a condition that checks the path:
However, this approach is not ideal as it conflicts with the auto-generation process and naming conventions of Nuxt's
server/api
folder. If a file is moved to a different folder and the middleware condition isn't updated accordingly, it can lead to application-breaking issues.Luckily there is a more elegant way to do it, you can use the
h3
onRequest
prop on your handler (see nuxt/nuxt#23308 (reply in thread)).CASE 2: Based on the
h3
syntax we can have:But this syntax brings other issues when your project starts to grow:
server/api
folder can become cluttered with numerous routes, making it challenging to review theonRequest
middleware list in each file.onRequest
middleware property.apiRouteAdminCheck
middleware or any other required middleware.Feature request:
h3
onRequest
syntax would be beneficial to define a list of paths, sub-paths, methods, or files that must be validated during build or startup to ensure they include a specified set of middleware.Current workaround:
Inspiration?:
Here's an example of how I reimplemented an inspired Nuxt
server/api
route auto-generation mechanism andh3
onRequest
logic in another project based onFastify
. The startup script for loading the routes also incorporates some of the checks mentioned earlier:In this case, the server would fail to start if the routes were not properly decorated, preventing the exposure of admin routes or no CSRF protection.
Representing the feature:
Let's say, you want to assure on startup or on build that :
/server/api/user
and/server/api/admin
has aisConnected
middleware/server/api/user
has aroleCheck
middleware/server/api/admin
has aadminOnly
middleware/server/api/2FA
has atwoFa
middlewareThere is currently no way to do it.
Raised in
nitrojs/nitro
after @danielroe commentAdditional information
Beta Was this translation helpful? Give feedback.
All reactions