allow-fields-must-be-global-middleware - ESLint plugin rules
This rule requires that allowFields, req.allowed, and req.disallowed are only set in a global middleware, not in a method-scoped one.
Severity#
error. This rule is enabled in the recommended preset.
What it Targets#
This rule targets the src/api/middlewares.ts file. It reports any middleware that uses allowFields, writes to req.allowed, or assigns req.disallowed when the route object includes a method or methods property.
Medusa validates the request's query parameters before it runs method-scoped middlewares, so setting allowed or disallowed fields in a method-scoped middleware has no effect.
The following code is reported by the rule:
Instead, remove the method property so the middleware applies to every request that matches the route:
src/api/middlewares.ts1import { allowFields, defineMiddlewares } from "@medusajs/framework/http"2 3export default defineMiddlewares({4 routes: [5 {6 matcher: "/store/products",7 middlewares: [allowFields("brand")],8 },9 ],10})
The same applies when writing to req.allowed or req.disallowed directly:
1// non-compliant — method-scoped2export default defineMiddlewares({3 routes: [4 {5 matcher: "/store/products",6 method: "GET",7 middlewares: [8 (req, res, next) => {9 req.allowed.push("brand")10 next()11 },12 ],13 },14 ],15})16 17// compliant — global middleware18export default defineMiddlewares({19 routes: [20 {21 matcher: "/store/products",22 middlewares: [23 (req, res, next) => {24 req.allowed.push("brand")25 next()26 },27 ],28 },29 ],30})
Why it's Important#
Medusa runs query-parameter validation before method-scoped middlewares execute. By the time a method-scoped middleware runs, the allowed or disallowed field lists are already applied, so any changes the middleware makes are ignored silently. To actually expand or restrict the retrievable fields, the middleware must be global (no method or methods property on the route).
Learn more in the Allowed Fields in API Routes documentation.
Fixable#
This rule isn't auto-fixable.