Skip to content

Commit fe3c284

Browse files
authored
docs: improve CORS troubleshooting guide (medusajs#14194)
1 parent 00052b9 commit fe3c284

File tree

10 files changed

+563
-25
lines changed

10 files changed

+563
-25
lines changed

www/apps/resources/app/integrations/guides/strapi/page.mdx

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1641,10 +1641,10 @@ import { createOptionsInStrapiStep } from "./steps/create-options-in-strapi"
16411641
import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
16421642
import {
16431643
CreateOptionValuesInStrapiInput,
1644-
createOptionValuesInStrapiStep
1644+
createOptionValuesInStrapiStep,
16451645
} from "./steps/create-option-values-in-strapi"
16461646
import {
1647-
updateProductOptionValuesMetadataStep
1647+
updateProductOptionValuesMetadataStep,
16481648
} from "./steps/update-product-option-values-metadata"
16491649

16501650
export type CreateOptionsInStrapiWorkflowInput = {
@@ -2121,7 +2121,7 @@ export const createVariantsInStrapiWorkflow = createWorkflow(
21212121
})
21222122

21232123
const strapiVariants = when({
2124-
variants
2124+
variants,
21252125
}, (data) => !!(data.variants[0].product as any)?.strapi_product)
21262126
.then(() => {
21272127
const variantImages = transform({
@@ -2158,7 +2158,7 @@ export const createVariantsInStrapiWorkflow = createWorkflow(
21582158
const variantsData = transform({
21592159
variants,
21602160
strapiVariantImages,
2161-
strapiVariantThumbnail
2161+
strapiVariantThumbnail,
21622162
}, (data) => {
21632163
const varData = data.variants.map((variant) => ({
21642164
id: variant.id,
@@ -2939,7 +2939,7 @@ export const handleStrapiWebhookWorkflow = createWorkflow(
29392939
const variants = updateProductVariantsWorkflow.runAsStep({
29402940
input: {
29412941
product_variants: [
2942-
preparedData.data as unknown as UpsertProductVariantDTO
2942+
preparedData.data as unknown as UpsertProductVariantDTO,
29432943
],
29442944
},
29452945
})
@@ -2988,7 +2988,7 @@ export const handleStrapiWebhookWorkflow = createWorkflow(
29882988
// Clear the product cache for all affected products
29892989
const productIds = transform({ variants }, (data) => {
29902990
const uniqueProductIds = [
2991-
...new Set(data.variants.map((v) => v.product_id))
2991+
...new Set(data.variants.map((v) => v.product_id)),
29922992
]
29932993
return uniqueProductIds as string[]
29942994
})
@@ -3815,7 +3815,7 @@ Then, find the `Text` component wrapping the `{product.description}` and replace
38153815
>
38163816
<Markdown
38173817
allowedElements={[
3818-
"p", "ul", "ol", "li", "strong", "em", "blockquote", "hr", "br", "a"
3818+
"p", "ul", "ol", "li", "strong", "em", "blockquote", "hr", "br", "a",
38193819
]}
38203820
unwrapDisallowed
38213821
>
Lines changed: 90 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,104 @@
1-
If you are experiencing connection issues when trying to access your Medusa application from a storefront or the admin dashboard, it is most likely due to Cross-Origin Resource Sharing (CORS) issues.
1+
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.
22

3-
You might see a log in your browser console, that looks like this:
3+
To verify it's a CORS error, check your [browser's console](https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Tools_and_setup/What_are_browser_developer_tools). You should see an error similar to the following:
44

5-
![CORS error log](https://res.cloudinary.com/dza7lstvk/image/upload/v1668003322/Medusa%20Docs/Other/jnHK115_udgf2n.png)
5+
```bash
6+
Access to fetch at 'http://localhost:9000/store/products' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
7+
```
8+
9+
## Why this Error Occurred
10+
11+
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.
12+
13+
---
14+
15+
## How to Fix It
16+
17+
### Verify Your CORS Settings
18+
19+
Medusa has three CORS settings that you can configure in your `medusa-config.ts` file:
620

7-
In your `medusa-config.ts`, ensure that you've configured your CORS settings correctly:
21+
1. [http.storeCors](!docs!/learn/configurations/medusa-config#httpstorecors): Allowed origins for requests to routes starting with `/store`. By default, it's set to `http://localhost:8000` for local development.
22+
2. [http.adminCors](!docs!/learn/configurations/medusa-config#httpadmincors): Allowed origins for requests to routes starting with `/admin`. By default, it's set to `http://localhost:9000` for local development.
23+
3. [http.authCors](!docs!/learn/configurations/medusa-config#httpauthcors): Allowed origins for requests to routes starting with `/auth`. By default, it's set to `http://localhost:8000,http://localhost:9000` for local development.
24+
25+
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.
26+
27+
For example, set the following environment variables in your `.env` file or in [Cloud](!cloud!/environments/environment-variables):
28+
29+
```env
30+
STORE_CORS=http://localhost:8000,http://my-custom-store.com
31+
ADMIN_CORS=http://localhost:9000,http://my-custom-admin.com
32+
AUTH_CORS=http://localhost:8000,http://localhost:9000,http://my-custom-store.com,http://my-custom-admin.com
33+
```
34+
35+
Then use the environment variables in your `medusa-config.ts` file:
836

937
```ts title="medusa-config.ts"
1038
module.exports = defineConfig({
1139
projectConfig: {
1240
http: {
13-
storeCors: process.env.STORE_CORS || "http://localhost:8000",
14-
adminCors: process.env.ADMIN_CORS || "http://localhost:9000",
15-
authCors: process.env.AUTH_CORS || "http://localhost:8000,http://localhost:9000",
41+
storeCors: process.env.STORE_CORS,
42+
adminCors: process.env.ADMIN_CORS,
43+
authCors: process.env.AUTH_CORS,
1644
},
1745
// ...
1846
},
1947
})
2048
```
2149

22-
Learn more about these configurations in [this documentation](!docs!/learn/configurations/medusa-config#http).
50+
### Apply CORS for Custom Route Prefix
51+
52+
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.
53+
54+
For example, if you create a custom route at `/custom-routes`, add a middleware to handle CORS for that route:
55+
56+
```ts title="src/api/middlewares.ts"
57+
import { defineMiddlewares } from "@medusajs/framework/http"
58+
import type {
59+
MedusaNextFunction,
60+
MedusaRequest,
61+
MedusaResponse,
62+
} from "@medusajs/framework/http"
63+
import { ConfigModule } from "@medusajs/framework/types"
64+
import { parseCorsOrigins } from "@medusajs/framework/utils"
65+
import cors from "cors"
66+
67+
export default defineMiddlewares({
68+
routes: [
69+
{
70+
matcher: "/custom-routes*",
71+
middlewares: [
72+
(
73+
req: MedusaRequest,
74+
res: MedusaResponse,
75+
next: MedusaNextFunction
76+
) => {
77+
const configModule: ConfigModule =
78+
req.scope.resolve("configModule")
79+
80+
return cors({
81+
origin: parseCorsOrigins(
82+
// Use the appropriate CORS setting for your custom route
83+
configModule.projectConfig.http.storeCors
84+
),
85+
credentials: true,
86+
})(req, res, next)
87+
},
88+
],
89+
},
90+
],
91+
})
92+
```
93+
94+
Make sure to:
95+
96+
- Update the `matcher` property to match your custom route path.
97+
- Pass the appropriate CORS setting for your custom route to `parseCorsOrigins`.
98+
99+
---
100+
101+
## Additional Resources
102+
103+
- [Medusa Configuration Options](!docs!/learn/configurations/medusa-config)
104+
- [CORS for Custom Routes](!docs!/learn/fundamentals/api-routes/cors#cors-in-custom-routes)

0 commit comments

Comments
 (0)