Fix CORS Error in Firebase Cloud Functions
Updated April 2026
Reading this article? Verify your fix in real-time. Test your Firebase Function CORS → CORSFixer
Firebase Cloud Functions do not add CORS headers automatically. You need to handle it yourself using the cors npm package or by setting headers manually.
Browser Console
Access to fetch at 'https://us-central1-yourproject.cloudfunctions.net/api' from origin 'https://yourapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Option 1 — cors npm package (recommended)
npm install cors
const functions = require("firebase-functions");
const cors = require("cors")({ origin: "https://yourapp.com" });
exports.myFunction = functions.https.onRequest((req, res) => { cors(req, res, () => { // Your function logic here res.json({ status: "ok" }); });
});
With Firebase Gen 2 functions (callable)
const { onRequest } = require("firebase-functions/v2/https");
const cors = require("cors")({ origin: "https://yourapp.com" });
exports.myFunction = onRequest((req, res) => { cors(req, res, () => { res.json({ data: "hello" }); });
});
Option 2 — manual headers
exports.myFunction = functions.https.onRequest((req, res) => { res.set("Access-Control-Allow-Origin", "https://yourapp.com"); res.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.set("Access-Control-Allow-Headers", "Content-Type, Authorization"); if (req.method === "OPTIONS") { res.status(204).send(""); return; } res.json({ status: "ok" });
});
Allow multiple origins
const cors = require("cors");
const corsHandler = cors({ origin: function(origin, callback) { const allowed = ["https://yourapp.com", "https://staging.yourapp.com"]; if (!origin || allowed.includes(origin)) { callback(null, true); } else { callback(new Error("Not allowed by CORS")); } }
});
exports.myFunction = functions.https.onRequest((req, res) => { corsHandler(req, res, () => { res.json({ status: "ok" }); });
});
Firebase Hosting rewrites (alternative)
If your frontend is on Firebase Hosting and your function is in the same project, configure a rewrite to proxy function calls — same origin, no CORS needed:
# firebase.json
{ "hosting": { "rewrites": [{ "source": "/api/**", "function": "myFunction" }] }
} Test your Firebase Function CORS → CORSFixer