4.6.9. Handling CORS in API Routes
In this chapter, you’ll learn about the CORS middleware and how to configure it for custom API routes.
CORS Overview#
Cross-Origin Resource Sharing (CORS) allows only configured origins to access your API Routes.
For example, if you allow only origins starting with http://localhost:7001 to access your Admin API Routes, other origins accessing those routes get a CORS error.
CORS Configurations#
The storeCors and adminCors properties of Medusa's http configuration set the allowed origins for routes starting with /store and /admin respectively.
These configurations accept a URL pattern to identify allowed origins.
For example:
This allows the http://localhost:7001 origin to access the Admin API Routes, and the http://localhost:8000 origin to access Store API Routes.
CORS in Store and Admin Routes#
To disable the CORS middleware for a route, export a CORS variable in the route file with its value set to false.
For example:
This disables the CORS middleware on API Routes at the path /store/custom.
CORS in Custom Routes#
If you create a route that doesn’t start with /store or /admin, you must apply the CORS middleware manually. Otherwise, all requests to your API route lead to a CORS error.
You can do that in the exported middlewares configurations in src/api/middlewares.ts.
For example:
12import cors from "cors"13 14export default defineMiddlewares({15 routes: [16 {17 matcher: "/custom*",18 middlewares: [19 (20 req: MedusaRequest, 21 res: MedusaResponse, 22 next: MedusaNextFunction23 ) => {24 const configModule: ConfigModule =25 req.scope.resolve(26 ContainerRegistrationKeys.CONFIG_MODULE27 )28 29 return cors({30 origin: parseCorsOrigins(31 configModule.projectConfig.http.storeCors32 ),33 credentials: true,34 })(req, res, next)35 },36 ],37 },38 ],39})
This retrieves the configurations exported from medusa-config.ts and applies the storeCors to routes starting with /custom.