|
4 | 4 | * This worker proxies requests to a backend API while maintaining cookies and handling CORS. |
5 | 5 | */ |
6 | 6 | export default { |
7 | | - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
8 | | - const url = new URL(request.url); |
| 7 | + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
| 8 | + const url = new URL(request.url); |
9 | 9 |
|
10 | | - // Determine if this is an API request that should be proxied |
11 | | - if (url.pathname.startsWith('/api/')) { |
12 | | - return await handleApiRequest(request, env, url); |
13 | | - } |
| 10 | + // Determine if this is an API request that should be proxied |
| 11 | + if (url.pathname.startsWith('/fly-api/')) { |
| 12 | + return await handleApiRequest(request, env, url); |
| 13 | + } |
14 | 14 |
|
15 | | - // For non-API requests, return a simple response or redirect |
16 | | - return new Response('This is a proxy worker. API requests should be sent to /api/...'); |
17 | | - }, |
| 15 | + // For non-API requests, return a simple response or redirect |
| 16 | + return new Response('This is a proxy worker. API requests should be sent to /fly-api/...'); |
| 17 | + }, |
18 | 18 | } satisfies ExportedHandler<Env>; |
19 | 19 |
|
20 | 20 | /** |
21 | 21 | * Handles API requests by proxying them to the backend |
22 | 22 | */ |
23 | 23 | async function handleApiRequest(request: Request, env: Env, url: URL): Promise<Response> { |
24 | | - // Configure your backend URL here |
25 | | - const backendUrl = 'https://your-app-name.fly.dev' + url.pathname + url.search; |
26 | | - |
27 | | - // Clone headers to a mutable object |
28 | | - const headers = new Headers(request.headers); |
29 | | - |
30 | | - // Forward the request to your API with all headers and the body |
31 | | - const modifiedRequest = new Request(backendUrl, { |
32 | | - method: request.method, |
33 | | - headers: headers, |
34 | | - body: request.body, |
35 | | - redirect: 'follow' |
36 | | - }); |
37 | | - |
38 | | - // Forward the request to your API |
39 | | - const response = await fetch(modifiedRequest); |
40 | | - |
41 | | - // Clone the response before we modify it |
42 | | - const responseData = await response.arrayBuffer(); |
43 | | - |
44 | | - // Create a new response with the data |
45 | | - const newResponse = new Response(responseData, { |
46 | | - status: response.status, |
47 | | - statusText: response.statusText, |
48 | | - }); |
49 | | - |
50 | | - // Copy all headers from the original response |
51 | | - response.headers.forEach((value, key) => { |
52 | | - // Skip the Set-Cookie header as we'll handle that specially |
53 | | - if (key.toLowerCase() !== 'set-cookie') { |
54 | | - newResponse.headers.set(key, value); |
55 | | - } |
56 | | - }); |
57 | | - |
58 | | - // Handle cookies specially |
59 | | - const setCookieHeaders = response.headers.getAll('Set-Cookie'); |
60 | | - if (setCookieHeaders && setCookieHeaders.length > 0) { |
61 | | - setCookieHeaders.forEach(cookie => { |
62 | | - const modifiedCookie = modifyCookie(cookie, request.url); |
63 | | - if (modifiedCookie) { |
64 | | - newResponse.headers.append('Set-Cookie', modifiedCookie); |
65 | | - } |
66 | | - }); |
67 | | - } |
68 | | - |
69 | | - // Add CORS headers to allow cross-domain requests |
70 | | - newResponse.headers.set('Access-Control-Allow-Origin', url.origin); |
71 | | - newResponse.headers.set('Access-Control-Allow-Credentials', 'true'); |
72 | | - newResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); |
73 | | - newResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); |
74 | | - |
75 | | - return newResponse; |
| 24 | + // Configure your backend URL here |
| 25 | + const backendUrl = 'https://your-app-name.fly.dev' + url.pathname + url.search; |
| 26 | + |
| 27 | + // Clone headers to a mutable object |
| 28 | + const headers = new Headers(request.headers); |
| 29 | + |
| 30 | + // Forward the request to your API with all headers and the body |
| 31 | + const modifiedRequest = new Request(backendUrl, { |
| 32 | + method: request.method, |
| 33 | + headers: headers, |
| 34 | + body: request.body, |
| 35 | + redirect: 'follow' |
| 36 | + }); |
| 37 | + |
| 38 | + // Forward the request to your API |
| 39 | + const response = await fetch(modifiedRequest); |
| 40 | + |
| 41 | + // Clone the response before we modify it |
| 42 | + const responseData = await response.arrayBuffer(); |
| 43 | + |
| 44 | + // Create a new response with the data |
| 45 | + const newResponse = new Response(responseData, { |
| 46 | + status: response.status, |
| 47 | + statusText: response.statusText, |
| 48 | + }); |
| 49 | + |
| 50 | + // Copy all headers from the original response |
| 51 | + response.headers.forEach((value, key) => { |
| 52 | + // Skip the Set-Cookie header as we'll handle that specially |
| 53 | + if (key.toLowerCase() !== 'set-cookie') { |
| 54 | + newResponse.headers.set(key, value); |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + // Handle cookies specially |
| 59 | + const setCookieHeaders = response.headers.getAll('Set-Cookie'); |
| 60 | + if (setCookieHeaders && setCookieHeaders.length > 0) { |
| 61 | + setCookieHeaders.forEach(cookie => { |
| 62 | + const modifiedCookie = modifyCookie(cookie, request.url); |
| 63 | + if (modifiedCookie) { |
| 64 | + newResponse.headers.append('Set-Cookie', modifiedCookie); |
| 65 | + } |
| 66 | + }); |
| 67 | + } |
| 68 | + |
| 69 | + // Add CORS headers to allow cross-domain requests |
| 70 | + newResponse.headers.set('Access-Control-Allow-Origin', url.origin); |
| 71 | + newResponse.headers.set('Access-Control-Allow-Credentials', 'true'); |
| 72 | + newResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); |
| 73 | + newResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); |
| 74 | + |
| 75 | + return newResponse; |
76 | 76 | } |
77 | 77 |
|
78 | 78 | /** |
79 | 79 | * Modifies cookies to ensure they work correctly across domains |
80 | 80 | */ |
81 | 81 | function modifyCookie(cookie: string, requestUrl: string): string | null { |
82 | | - if (!cookie) return null; |
83 | | - |
84 | | - const url = new URL(requestUrl); |
85 | | - const cookieParts = cookie.split(';').map(part => part.trim()); |
86 | | - const mainPart = cookieParts[0]; // This contains name=value |
87 | | - |
88 | | - // Create a new array for the modified cookie parts |
89 | | - const newCookieParts = [mainPart]; |
90 | | - |
91 | | - // Keep track if we've seen these attributes |
92 | | - let hasDomain = false; |
93 | | - let hasSameSite = false; |
94 | | - let hasSecure = false; |
95 | | - |
96 | | - // Process all cookie attributes except the main part |
97 | | - for (let i = 1; i < cookieParts.length; i++) { |
98 | | - const part = cookieParts[i].toLowerCase(); |
99 | | - |
100 | | - // Check for existing attributes |
101 | | - if (part.startsWith('domain=')) { |
102 | | - // Replace domain with the domain from the request URL |
103 | | - newCookieParts.push(`Domain=${url.hostname}`); |
104 | | - hasDomain = true; |
105 | | - } else if (part.startsWith('samesite=')) { |
106 | | - // Keep original SameSite or set to None for cross-domain cookies |
107 | | - newCookieParts.push('SameSite=None'); |
108 | | - hasSameSite = true; |
109 | | - } else if (part === 'secure') { |
110 | | - newCookieParts.push('Secure'); |
111 | | - hasSecure = true; |
112 | | - } else { |
113 | | - // Keep all other attributes as they are |
114 | | - newCookieParts.push(cookieParts[i]); |
115 | | - } |
116 | | - } |
117 | | - |
118 | | - // Add missing attributes if needed |
119 | | - if (!hasDomain) { |
120 | | - newCookieParts.push(`Domain=${url.hostname}`); |
121 | | - } |
122 | | - |
123 | | - if (!hasSameSite) { |
124 | | - newCookieParts.push('SameSite=None'); |
125 | | - } |
126 | | - |
127 | | - if (!hasSecure) { |
128 | | - newCookieParts.push('Secure'); |
129 | | - } |
130 | | - |
131 | | - return newCookieParts.join('; '); |
| 82 | + if (!cookie) return null; |
| 83 | + |
| 84 | + const url = new URL(requestUrl); |
| 85 | + const cookieParts = cookie.split(';').map(part => part.trim()); |
| 86 | + const mainPart = cookieParts[0]; // This contains name=value |
| 87 | + |
| 88 | + // Create a new array for the modified cookie parts |
| 89 | + const newCookieParts = [mainPart]; |
| 90 | + |
| 91 | + // Keep track if we've seen these attributes |
| 92 | + let hasDomain = false; |
| 93 | + let hasSameSite = false; |
| 94 | + let hasSecure = false; |
| 95 | + |
| 96 | + // Process all cookie attributes except the main part |
| 97 | + for (let i = 1; i < cookieParts.length; i++) { |
| 98 | + const part = cookieParts[i].toLowerCase(); |
| 99 | + |
| 100 | + // Check for existing attributes |
| 101 | + if (part.startsWith('domain=')) { |
| 102 | + // Replace domain with the domain from the request URL |
| 103 | + newCookieParts.push(`Domain=${url.hostname}`); |
| 104 | + hasDomain = true; |
| 105 | + } else if (part.startsWith('samesite=')) { |
| 106 | + // Keep original SameSite or set to None for cross-domain cookies |
| 107 | + newCookieParts.push('SameSite=None'); |
| 108 | + hasSameSite = true; |
| 109 | + } else if (part === 'secure') { |
| 110 | + newCookieParts.push('Secure'); |
| 111 | + hasSecure = true; |
| 112 | + } else { |
| 113 | + // Keep all other attributes as they are |
| 114 | + newCookieParts.push(cookieParts[i]); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // Add missing attributes if needed |
| 119 | + if (!hasDomain) { |
| 120 | + newCookieParts.push(`Domain=${url.hostname}`); |
| 121 | + } |
| 122 | + |
| 123 | + if (!hasSameSite) { |
| 124 | + newCookieParts.push('SameSite=None'); |
| 125 | + } |
| 126 | + |
| 127 | + if (!hasSecure) { |
| 128 | + newCookieParts.push('Secure'); |
| 129 | + } |
| 130 | + |
| 131 | + return newCookieParts.join('; '); |
132 | 132 | } |
0 commit comments