1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Define a common set of CORS headers
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
export default async function(req: Request): Promise<Response> {
// Check if the request is an OPTIONS request
if (req.method === "OPTIONS") {
// Create a response for the OPTIONS request
return new Response(null, {
status: 204, // No Content
headers: {
...corsHeaders,
"Access-Control-Max-Age": "86400", // 24 hours
},
});
}
// Parse the request URL
const incomingUrl = new URL(req.url);
// Extract the pathname and decode it to get the destination URL
// Assuming the pathname is encoded and represents the destination URL
const destUrlString = decodeURIComponent(incomingUrl.pathname.slice(1)); // Remove the leading slash
// Validate the destination URL
try {
new URL(destUrlString); // This is just to validate the URL
} catch (error) {
return new Response(JSON.stringify({ error: "Invalid destination URL" }), {
status: 400, // Bad Request
headers: {
"Content-Type": "application/json",
...corsHeaders,
},
});
}
// Set up the headers for the new request
const headers = new Headers(req.headers);
// Optionally, remove or modify headers that should not be forwarded
headers.delete("Host");
// Prepare the request options
const init = {
method: req.method,
headers: headers,
body: req.body,
};
// Perform the fetch request to the destination URL
const response = await fetch(destUrlString, init);
// Return the response from the destination URL, including CORS headers
return new Response(response.body, {
status: response.status,
headers: {
...response.headers,
...corsHeaders, // Spread the CORS headers
},
});
}