Owen Conti

Create a Reverse Proxy with Cloudflare Workers

Posted on under Devops by Owen Conti.

This is my first pass at a reverse proxy script using Cloudflare Workers. It's pretty simple.

1addEventListener("fetch", (event) => {
2 event.respondWith(
3 handleRequest(event.request).catch(
4 (err) => new Response(err.stack, { status: 500 })
5 )
6 );
7});
8 
9async function handleRequest(request) {
10 const { search } = new URL(request.url);
11 
12 const params = new URLSearchParams(search);
13 params.set('token', OHSEESNAPS_TOKEN);
14 
15 return fetch(`https://ohseesnaps.com/api/snap?${params.toString()}`)
16}

This worker does the following:

  1. Takes the query parameters from the request

  2. Adds a token parameter pulled from an environment variable, OHSEESNAPS_TOKEN

  3. Sends a request to the proxied server, https://ohseesnaps.com/api/snap

  4. When sending the request to the proxied server, the original query parameters (including the added token parameter) are sent as well

  5. The response from the proxied server is sent back to the client


Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on X!

Found an issue with the article? Submit your edits against the repository.