Created
January 6, 2023 23:02
-
-
Save obumnwabude/adc545b11da5424ef67d0f1e5193da31 to your computer and use it in GitHub Desktop.
Firebase Cloud Functions Code for CORS proxy.
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
const admin = require('firebase-admin'); | |
const cors = require('cors')({ origin: true }); | |
const fetch = require('node-fetch'); | |
const functions = require('firebase-functions'); | |
exports.cors = functions.https.onRequest((req, res) => { | |
// Reject requests that don't have a URL. | |
if (!req.query.url) return res.json({ error: 'No URL provided!' }); | |
// Extract necessary information from the request. | |
const { body, headers, method } = req; | |
// deleting these headers prevents the following error: | |
// "Hostname/IP does not match certificate's altnames" | |
// | |
// See this GitHub issue answer for more | |
// https://github.com/node-fetch/node-fetch/discussions/1678#discussioncomment-4191424 | |
delete headers.host; | |
delete headers.referer; | |
// Create the "options" object for the fetch request. | |
const options = { headers, method }; | |
// Add the body to "options", if it exists and if this is not a GET request. | |
if (body && method !== 'GET') options.body = body; | |
// Send the request to the URL provided and return the response. | |
// Wrapping fetch in cors() sets the necessary CORS headers. | |
return cors(req, res, () => | |
// decoding the URI is important if in case queries were pre-encoded. | |
fetch(decodeURI(req.query.url), options) | |
.then((r) => | |
r.headers.get('content-type') === 'application/json' | |
? r.json() | |
: r.text() | |
) | |
.then((r) => res.send(r)) | |
.catch((e) => res.json({ error: e.message })) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment