Building a CORS-Enabled Proxy Server with Cloudflare Workers
Cross-Origin Resource Sharing (CORS) can be a real headache for developers working on web applications, especially when accessing APIs hosted on different domains. Modern browsers restrict such requests for security reasons, and while many APIs support CORS, some don’t. This is where a CORS proxy comes in handy.
What is a CORS Proxy?
A CORS proxy acts as a middleman between your application and the target API. When you make a request to the CORS proxy, it forwards your request to the target server, receives the response, and then forwards it back to you. The proxy adds the necessary CORS headers to bypass restrictions on your front end.
Step 1: Setting Up a Cloudflare Worker
- Sign Up: If you don’t have a Cloudflare account, sign up for free at Cloudflare.
- Navigate to Workers: In the Cloudflare dashboard, go to Workers and create a new service.
- Create Service: Give your service a name and select HTTP Handler as the template type, which will let us handle incoming HTTP requests.
Step 2: Writing the Proxy Code
Once your Worker is set up, we’ll add the code to create the CORS proxy. Here’s the JavaScript code to use:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
const targetUrl = url.searchParams.get('url') // Get the target URL from the `url` query parameter
if (!targetUrl) {
return new Response('Missing "url" query parameter', { status: 400 })
}
// Clone headers and set Content-Type to application/json if needed
const headers = new Headers(request.headers)
headers.set('Content-Type', 'application/json')
// Create a request for the target URL
const targetRequest = new Request(targetUrl, {
method: request.method,
headers: headers,
body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : null,
})
try {
const response = await fetch(targetRequest)
// Add CORS headers to allow all origins
const newHeaders = new Headers(response.headers)
newHeaders.set('Access-Control-Allow-Origin', '*')
newHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
newHeaders.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
return new Response(response.body, {
status: response.status,
headers: newHeaders
})
} catch (error) {
return new Response('Error fetching the target URL', { status: 500 })
}
}
Step 3: Deploying the Worker
After adding the code, click Save and Deploy in the Cloudflare Workers dashboard. Your CORS proxy is now live! The Worker URL will look something like this:
https://your-worker.your-subdomain.workers.dev
Step 4: Using the Proxy in Your Frontend
With your CORS proxy live, you can now call it from your frontend application. Here’s an example JavaScript function to fetch data through the proxy and display it:
function fetchData() {
const targetUrl = 'https://example.com/api/data';
const proxyUrl = `https://your-worker.your-subdomain.workers.dev/?url=${encodeURIComponent(targetUrl)}`;
fetch(proxyUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
This function sends a GET
request to your proxy, which then fetches data from the target URL and returns it to the frontend. You can adjust this function to handle and display the data as needed.
It can be from just react, plain javascript, vue or angular based which need an API access but having the CORS problem.
Comment if you think you got the right solution.
This is a fix for :
Webflow Cors issue
Webflow API cors issue
React API cors issue
React cors issue
Vue.js cors