Allow all origins with a CORS header proxy
A few years ago, I tried to set up a CORS header proxy using cors-anywhere. However, I never got it to work and I just deleted it.
This time, I again needed a proxy that allows all origins to access a service. I happened to see the comment by Robin Linacre on GitHub and learned that Cloudflare has made their own CORS header proxy and you can single-click to Deploy to Cloudflare. And that’s exactly what I did.
The only caveat is that Cloudflare’s proxy only allows the origin to be the worker itself. So we need to update that line of code to allow all origins.
// Set CORS headers response.headers.set('Access-Control-Allow-Origin', url.origin) response.headers.set('Access-Control-Allow-Origin', '*')Once it finishes deploying to Cloudflare Workers, you can now access any service without
CORS restrictions using https://REDACTED.REDACTED.workers.dev/corsproxy/?apiurl={YOUR_URL_HERE}.
That’s it!
Results
Section titled “Results”I tested the proxy by fetching https://example.com from the browser’s dev console while on the Google home page.
Without proxy
Section titled “Without proxy”fetch('https://example.com') .then(r => r.text()) .then(console.log) .catch(console.error);Access to fetch at 'https://example.com/' from origin 'https://www.google.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.With proxy
Section titled “With proxy”fetch('https://REDACTED.REDACTED.workers.dev/corsproxy/?apiurl=https://example.com') .then(r => r.text()) .then(console.log) .catch(console.error);<!doctype html><html lang="en"><head><title>Example Domain</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{background:#eee;width:60vw;margin:15vh auto;font-family:system-ui,sans-serif}h1{font-size:1.5em}div{opacity:0.8}a:link,a:visited{color:#348}</style></head><body><div><h1>Example Domain</h1><p>This domain is for use in documentation examples without needing permission. Avoid use in operations.</p><p><a href="https://iana.org/domains/example">Learn more</a></p></div></body></html>