1+ export default {
2+ async fetch ( request , env , ctx ) {
3+ // 1. Define your target (Render)
4+ const TARGET_URL = "https://random-rants-plus.onrender.com" ;
5+
6+ // 2. Parse the incoming request URL
7+ const url = new URL ( request . url ) ;
8+ const target = new URL ( TARGET_URL ) ;
9+
10+ // 3. Copy the path and query params (e.g., /socket.io/?EIO=4...)
11+ url . hostname = target . hostname ;
12+ url . protocol = target . protocol ;
13+ url . port = target . port ;
14+
15+ // 4. Handle WebSocket Upgrades specifically
16+ const upgradeHeader = request . headers . get ( 'Upgrade' ) ;
17+ if ( upgradeHeader === 'websocket' ) {
18+ return await handleWebSocket ( request , url ) ;
19+ }
20+
21+ // 5. Handle Standard HTTP Requests (GET, POST, PUT, etc.)
22+ // We create a new request with the same body and headers
23+ const newRequest = new Request ( url , {
24+ method : request . method ,
25+ headers : request . headers ,
26+ body : request . body ,
27+ redirect : 'follow'
28+ } ) ;
29+
30+ // 6. Send to Render and return the response
31+ return fetch ( newRequest ) ;
32+ }
33+ } ;
34+
35+ // Helper function to handle the WebSocket handshake
36+ async function handleWebSocket ( request , url ) {
37+ // Create a new request specifically for the WebSocket handshake
38+ const wsRequest = new Request ( url , {
39+ method : request . method ,
40+ headers : request . headers ,
41+ redirect : 'follow'
42+ } ) ;
43+
44+ // Fetch the remote WebSocket
45+ const response = await fetch ( wsRequest ) ;
46+
47+ // If the remote server accepted the upgrade (Status 101), return it
48+ if ( response . status === 101 ) {
49+ // Cloudflare Workers automatically handles the piping of the WebSocket
50+ return response ;
51+ }
52+
53+ // If it failed, return the error
54+ return response ;
55+ }
0 commit comments