CORS Errors
If you're experiencing connection issues when trying to access your Medusa application's API routes from the storefront, admin dashboard, or any client application, it's most likely due to a Cross-Origin Resource Sharing (CORS) error.
To verify it's a CORS error, check your browser's console. You should see an error similar to the following:
Why this Error Occurred#
This error occurs when you try to access the Medusa server's API routes from a domain that isn't configured in the application's CORS settings. By default, Medusa only allows requests from specific origins to ensure security.
How to Fix It#
Verify Your CORS Settings#
Medusa has three CORS settings that you can configure in your medusa-config.ts file:
- http.storeCors: Allowed origins for requests to routes starting with
/store. By default, it's set tohttp://localhost:8000for local development. - http.adminCors: Allowed origins for requests to routes starting with
/admin. By default, it's set tohttp://localhost:9000for local development. - http.authCors: Allowed origins for requests to routes starting with
/auth. By default, it's set tohttp://localhost:8000,http://localhost:9000for local development.
If your storefront or admin are hosted at different domains or ports, or if you're accessing Medusa's API routes from a different origin (such as an additional storefront), you'll need to update the CORS settings accordingly. You can add additional origins by separating them with commas.
For example, set the following environment variables in your .env file or in Cloud:
Then use the environment variables in your medusa-config.ts file:
Apply CORS for Custom Route Prefix#
Medusa applies its CORS settings to routes starting with /store, /admin, and /auth. If you've created a route whose path doesn't start with one of these prefixes, you must manually handle CORS for that route.
For example, if you create a custom route at /custom-routes, add a middleware to handle CORS for that route:
1import { defineMiddlewares } from "@medusajs/framework/http"2import type { 3 MedusaNextFunction, 4 MedusaRequest, 5 MedusaResponse, 6} from "@medusajs/framework/http"7import { ConfigModule } from "@medusajs/framework/types"8import { parseCorsOrigins } from "@medusajs/framework/utils"9import cors from "cors"10 11export default defineMiddlewares({12 routes: [13 {14 matcher: "/custom-routes*",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 // Use the appropriate CORS setting for your custom route27 configModule.projectConfig.http.storeCors28 ),29 credentials: true,30 })(req, res, next)31 },32 ],33 },34 ],35})
Make sure to:
- Update the
matcherproperty to match your custom route path. - Pass the appropriate CORS setting for your custom route to
parseCorsOrigins.