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:
Takes the query parameters from the request
Adds a
token
parameter pulled from an environment variable,
OHSEESNAPS_TOKEN
Sends a request to the proxied server,
https://ohseesnaps.com/api/snap
When sending the request to the proxied server, the original query parameters (including the added
token
parameter) are sent as well
The response from the proxied server is sent back to the client
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.