Worker CORS for Pages App

What is the name of the domain?

ethang.dev

What is the issue you’re encountering

Pages domain blocked by worker CORS

What steps have you taken to resolve the issue?

  • Tried multiple methods
  • Asked AI
  • Search internet

What are the steps to reproduce the issue?

Worker root file: ethang-monorepo/apps/auth/src/index.ts at master · eglove/ethang-monorepo · GitHub

Utility that adds CORS headers to all responses: ethang-monorepo/apps/auth/src/utils/util.ts at master · eglove/ethang-monorepo · GitHub

If I also just use ‘*’ as Access-Control-Allow-Origin, CORS is blocked. I am trying to make this only work with subdomains of ethang.dev.

Screenshot of the error

2025-01-14 17_37_32-EthanG _ Looking At_ No Misused Spread - Brave.png

Helpful article:

May I ask if you are going to use a custom domain, or rather sub-domain, or not at all for the particular R2 bucket? :thinking:

Connect the custom domain to your R2 bucket, then add the missing Access-Control-Allow-Origin HTTP header by using Transform Rules → Modify Response Header as follows:

Helpful article with the step-by-step instructions how to create one:

With a couple of small fixes I got everything working. Here’s the important parts.

These are the default headers for all responses:

{
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
    "Access-Control-Allow-Origin": "",
  }

Note the first two properties. Allow-Headers: Content-Type is needed for the frontend to send JSON on the response. And allowed methods are everything allowed + OPTIONS for the preflight request.

Then I look at the ‘Origin’ header and make sure it ends with the main domain. This way any subdomain works. I then set Access-Control-Allow-Origin to that origin:

if (!isNil(origin) && endsWith(origin, "ethang.dev")) {
      store.setOrigin(origin); // Set header that will be on **Response**
}

When the header is OPTIONS, I send back a OK response with a null body. This is for the CORS check.

After that all responses add the above headers with the origin of the original request. The full updated code is in the links in the original post.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.