Skip to content

Instantly share code, notes, and snippets.

@lox
Last active August 31, 2023 09:58
Show Gist options
  • Save lox/8614c907d64ddd79392d338866d6f8b9 to your computer and use it in GitHub Desktop.
Save lox/8614c907d64ddd79392d338866d6f8b9 to your computer and use it in GitHub Desktop.
Cloudflare worker for rewriting a custom domain to work with Firebase SDK
import { initializeFirestore } from 'firebase/firestore'
const db = initializeFirestore(app, { host: 'firestore-rewrite.xxx.workers.dev' })
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request))
})
/**
* Intercept requests and redirect to Firestore API
* @param {Request} request
*/
async function handleRequest(request) {
const url = new URL(request.url)
// Modify the URL to point to Firestore API
url.protocol = 'https'
url.host = 'firestore.googleapis.com'
// Construct a new request object
const newRequest = new Request(url, {
method: request.method,
headers: request.headers,
body: request.body,
})
// Fetch the Firestore API and get the response
let response = await fetch(newRequest)
// Clone response so you can modify headers
const clonedResponse = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: new Headers(response.headers),
})
// Remove any existing CORS headers to avoid conflicts
clonedResponse.headers.delete('Access-Control-Allow-Origin')
clonedResponse.headers.delete('Access-Control-Allow-Methods')
clonedResponse.headers.delete('Access-Control-Allow-Headers')
// Add our own CORS headers
// We need to be specific because the request sets Access-Control-Allow-Credentials which
// doesn't allow a wildcard for Access-Control-Allow-Origin
const origin = request.headers.get('Origin') || 'http://localhost:3000';
clonedResponse.headers.set('Access-Control-Allow-Origin', origin)
clonedResponse.headers.set('Access-Control-Allow-Methods', 'GET,HEAD,POST,OPTIONS')
clonedResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type')
clonedResponse.headers.set('Access-Control-Allow-Credentials', 'true')
return clonedResponse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment