Add CORS Headers to Redirect Rules

Type

Product improvement

Description

Allow users to configure CORS headers (like Access-Control-Allow-Origin) directly in Redirect Rules.

Benefit

I’d love to see support for CORS headers in Redirect Rules. Especially for simple redirects that need to work in a cross-origin context.

Currently, I have to write custom Workers just to add CORS support. For example, I use this Worker to redirect to an external endpoint while handling both regular and preflight (OPTIONS) requests:

export default {
  async fetch(request) {
    const { method, url } = request;
    const parsedUrl = new URL(url);

    // Handle CORS preflight (OPTIONS) requests for all paths
    if (method === 'OPTIONS') {
      return new Response(null, {
        status: 204,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type', // Adjust as needed
          'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', // Add POST, DELETE, PUT as needed
          'Access-Control-Max-Age': '86400', // Cache preflight requests for 24 hours
        },
      });
    }

    // Restrict to GET and HEAD requests, adjust as needed
    if (
      (method === 'GET' || method === 'HEAD') &&
      parsedUrl.pathname === '/api/myresource'
    ) {
      const redirectUrl = 'https://coinos.io/.well-known/lnurlp/anthony.accioly';
      return new Response(null, {
        status: 302, // Change this to 307 if you want POST, etc to be changed to GET
        headers: {
          'Location': redirectUrl,
          'Cache-Control': 'public, max-age=300, s-maxage=300', // Cache the redirect for 5 minutes - Cloudflare won't cache it, but the browser and other caches will
          'Access-Control-Allow-Origin': '*',
        },
      });
    }
  }
}

Even having just a checkbox to enable Access-Control-Allow-Origin: * would already be extremely useful. Support for other CORS headers (Allow-Headers, Allow-Methods, Max-Age) and preflight OPTIONS handling would make it even more powerful and flexible.

Related post from 2019: Page rules do not forward CORS

Benefits:

  • Simplifies common cross-origin redirect use cases
  • Avoids unnecessary Worker usage for basic scenarios
  • Reduces setup complexity and potential CORS issues
  • Makes Redirect Rules more versatile and self-contained
  • Helps developers integrate with APIs, .well-known endpoints, or any cross-origin resources more easily