To enable Cross-Origin Resource Sharing (CORS) in Cloud Functions for Firebase, you must use the cors middleware, an npm package that helps manage CORS in your HTTP functions.
Here’s a step-by-step guide on how to enable CORS in your Firebase Cloud Functions:
Step 1: Install the cors package
First, navigate to your Firebase Cloud Functions folder and install the cors
package by running the following command.
npm install cors
Step 2: Import the cors package inside your project file
Next, import the cors package in your index.js or index.ts file (depending on whether you’re using JavaScript or TypeScript) and initialize it with your desired options.
const functions = require('firebase-functions');
const cors = require('cors');
// Configure CORS options
const corsOptions = {
// Replace with your desired domain or
// an array of allowed domains
origin: '*',
// Some legacy browsers (IE11, various SmartTVs) choke on 204
optionsSuccessStatus: 200
};
// Create the CORS middleware
const corsMiddleware = cors(corsOptions);
To restrict the allowed origins, you can replace the ‘*’ with your specific domain (e.g., ‘https://abc.com’) or an array of allowed domains (e.g., [‘https://abc.com’, ‘https://another-abc.com’]).
Step 3: Applying the CORS middleware
Finally, apply the corsMiddleware
to your Firebase Cloud Function by wrapping your function with the middleware.
exports.yourFunction = functions.https.onRequest((request, response) => {
corsMiddleware(request, response, () => {
// Your function's code goes here
response.send('Hello from Firebase with CORS enabled!');
});
});
With these changes, your Firebase Cloud Function will enable CORS, allowing your specified origins to access the function.
If you have multiple functions, apply the corsMiddleware to each, as shown in step 3.
That’s it.

Amit Doshi is a Cloud Engineer who has experienced more than 5 years in AWS, Azure, and Google Cloud. He is an IT professional responsible for designing, implementing, managing, and maintaining cloud computing infrastructure, applications, and services.