Created
April 5, 2024 14:34
-
-
Save katspaugh/b5816d8462808962bd923e51b854d737 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(handleSSE(event.request)) | |
}); | |
const sseServerUrl = 'https://safe-events.safe.global/events/sse'; | |
async function handleSSE(request) { | |
// Parse the incoming request URL | |
const incomingUrl = new URL(request.url); | |
// Extract the path from the incoming request, if necessary | |
// If you always proxy to a fixed path, this might not be needed | |
const path = incomingUrl.pathname; | |
// Complete URL to the SSE endpoint | |
const fullUrl = sseServerUrl + path; | |
// Initialize a new request to the SSE server | |
const modifiedRequest = new Request(fullUrl, { | |
method: 'GET', // SSE typically uses GET | |
headers: new Headers({ | |
'Authorization': 'Basic ' + AUTH_HEADER, | |
// The original request to the SSE server should not contain CORS headers | |
}), | |
}); | |
// Fetch the stream from the SSE server | |
const response = await fetch(modifiedRequest); | |
// Ensure the response is a stream and keep the headers to set on the response | |
const { readable, writable } = new TransformStream(); | |
response.body.pipeTo(writable); | |
// Clone the response headers from the SSE server so we can modify them | |
const newHeaders = new Headers(response.headers); | |
// Add/Override CORS headers in the response back to the client | |
newHeaders.set('Access-Control-Allow-Origin', '*'); // Adjust as per your security requirements | |
newHeaders.set('Access-Control-Allow-Methods', 'GET, OPTIONS'); | |
newHeaders.set('Access-Control-Allow-Headers', 'Authorization, Content-Type'); | |
newHeaders.set('Access-Control-Expose-Headers', '*'); // Be cautious with exposing all headers | |
newHeaders.set('Access-Control-Max-Age', '86400'); // 24 hours | |
// Return a new response with the stream and necessary headers | |
return new Response(readable, { | |
headers: newHeaders, | |
status: response.status | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment