Skip to content

Instantly share code, notes, and snippets.

@ilmpc
Created October 30, 2022 10:10
Show Gist options
  • Select an option

  • Save ilmpc/7058bb22f8a15bfe30f90b77873d730d to your computer and use it in GitHub Desktop.

Select an option

Save ilmpc/7058bb22f8a15bfe30f90b77873d730d to your computer and use it in GitHub Desktop.
Cloudflare function for api proxing
// The URL for the remote third party API you want to fetch from
// but does not implement CORS
const API_URL = 'https://api.example.com/api/';
export const onRequest = async (context) => {
const url = context.request.url.replace(/https?:\/\/.+?\/api\//gi, API_URL);
// Rewrite request to point to API URL. This also makes the request mutable
// so you can add the correct Origin header to make the API server think
// that this request is not cross-site.
const request = new Request(url, context.request);
request.headers.set('Origin', new URL('http://localhost:3000').origin);
let response = await fetch(request);
// Recreate the response so you can modify the headers
response = new Response(response.body, response);
// Remove CORS headers
response.headers.delete('Access-Control-Allow-Origin');
response.headers.delete('Access-Control-Allow-Credentials');
return response;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment