4.1.5. 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#

You configure allowed origins for Store and Admin API Routes using the storeCors and adminCors properties of the http configuration in medusa-config.js. Each of these configurations accepts a URL pattern to identify allowed origins.

For example:

medusa-config.js
1module.exports = defineConfig({2  projectConfig: {3    http: {4      storeCors: "http://localhost:8000",5      adminCors: "http://localhost:7001",6      // ...7    },8  },9})

This allows the http://localhost:7001 origin to access the Admin API Routes, and the http://localhost:8000 origin to access Store API Routes.

Tip

Learn more about the CORS configurations in this resource guide.


CORS in Store and Admin Routes#

Medusa applies the CORS middleware with the specified configurations in medusa-config.js on all routes starting with /store and /admin.

To disable the CORS middleware for a route, export a CORS variable in the route file with its value set to false.

For example:

src/api/store/custom/route.ts
1import type { 2  MedusaRequest, 3  MedusaResponse,4} from "@medusajs/medusa"5
6export const GET = (7  req: MedusaRequest,8  res: MedusaResponse9) => {10  res.json({11    message: "[GET] Hello world!",12  })13}14
15export const CORS = false

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:

src/api/middlewares.ts
9import cors from "cors"10
11export const config: MiddlewaresConfig = {12  routes: [13    {14      matcher: "/custom*",15      middlewares: [16        (17          req: MedusaRequest, 18          res: MedusaResponse, 19          next: MedusaNextFunction20        ) => {21          const configModule: ConfigModule =22            req.scope.resolve("configModule")23
24          return cors({25            origin: parseCorsOrigins(26              configModule.projectConfig.http.storeCors27            ),28            credentials: true,29          })(req, res, next)30        },31      ],32    },33  ],34}

This retrieves the configurations exported from medusa-config.js and applies the storeCors to routes starting with /custom.

Was this chapter helpful?