This guide walks through setting up an API proxy using Cloudflare Workers, allowing you to mask API requests, enforce security, and add rate limiting.
This is useful, as it allows us to securely fetch recipes through a proxy, protect the API key, and address common issues like CORS while also adding flexibility to the application.
api-proxy
).Replace <TARGET_API>
with the real API URL and <YOUR_SECRET_TOKEN>
with an example token.
export default {
async fetch(request) {
const url = new URL(request.url);
const apiKey = "<YOUR_SECRET_TOKEN>";
const htbApiBaseUrl = "<TARGET_API>";
const challengeName = url.searchParams.get("challenge");
if (!challengeName) {
return new Response(JSON.stringify({ error: "name is required" }), { status: 400 });
}
const targetUrl = `${htbApiBaseUrl}/${encodeURIComponent(challengeName)}`;
try {
const response = await fetch(targetUrl, {
method: "GET",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json"
}
});
if (!response.ok) {
return new Response(JSON.stringify({ error: "Failed to fetch challenge data" }), { status: response.status });
}
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
});
} catch (error) {
return new Response(JSON.stringify({ error: "Server error" }), {
status: 500,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
});
}
},
};
proxy.example.com
(or any desired subdomain).CNAME
proxy
<worker-name>.<your-cloudflare-zone>.workers.dev
Use cURL or a browser to confirm that requests are being proxied correctly.
curl https://proxy.example.com/?challenge=value
If everything is set up properly, you should see a successful response from the original API.