CORS Firebase Configuration

User
Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/v0/b/openeratech.firebasestorage.app/o?name=portfolio%2F1742542411774_tab-1.png' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
performing firebase cloud storage opertion from local server localhost:5173 to firebase and given above error
Assistant
The error you're encountering:

Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/...' from origin 'http://localhost:5173' has been blocked by CORS policy...

means that **CORS (Cross-Origin Resource Sharing)** is not properly configured on your Firebase Cloud Storage bucket.

### ✅ Solution: Configure Firebase Storage CORS

You need to allow requests from your local development domain (`http://localhost:5173`) by updating your Firebase Storage CORS rules.

#### Step 1: Install Firebase CLI (if not already installed)

npm install -g firebase-tools

#### Step 2: Authenticate with Firebase

firebase login

#### Step 3: Initialize or use existing Firebase project

firebase use --add

#### Step 4: Create a CORS configuration file `cors.json`:

[
  {
    "origin": ["http://localhost:5173"],
    "method": ["GET", "POST", "PUT", "DELETE"],
    "maxAgeSeconds": 3600,
    "responseHeader": ["Content-Type", "Authorization", "x-goog-meta-*"]
  }
]

#### Step 5: Apply the CORS configuration to your storage bucket

firebase storage:bucket

Note down your bucket name, for example:
`openeratech.firebasestorage.app`

Then run:

gsutil cors set cors.json gs://openeratech.firebasestorage.app

> If you don’t have `gsutil`, you can install it by installing the [Google Cloud SDK](https://cloud.google.com/sdk/docs/install).

### ⚠️ Note:
– Make sure you're authenticated to the same Firebase project in `gsutil` or your Firebase CLI.
– If your request is **authenticated**, include `Authorization` headers and allow them in `responseHeader`.

### ✅ After Applying Changes
Wait for a few minutes for the CORS settings to propagate, then restart your local dev server and retry the request.

Let me know if you're uploading files from your frontend too — the CORS rules might need to include `OPTIONS` if you’re making preflighted requests.

User
we are using free project
Assistant
Thanks for clarifying that you're using the **Firebase Free Tier (Spark Plan)**.

Here’s what you need to know:

### 🚫 Spark Plan Limitation

Firebase **Spark Plan does _not_ support custom CORS settings via `gsutil` or Google Cloud Console**, because you don’t get full access to Google Cloud Storage features — especially when it comes to modifying bucket metadata (like CORS rules).

### ✅ Workaround Options

#### Option 1: **Use Firebase Hosting with Storage**
If you serve your frontend (instead of `localhost:5173`) via Firebase Hosting (which is allowed in the Spark plan), and access Storage via authenticated Firebase SDK calls, you **won’t hit CORS issues**.

So instead of:

http://localhost:5173

You deploy your frontend to:

https://your-project-id.web.app

Use Firebase SDK for accessing files, e.g.:

import { getStorage, ref, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const imageRef = ref(storage, "portfolio/1742542411774_tab-1.png");

getDownloadURL(imageRef).then((url) => {
  // use the image URL in your app
}).catch((error) => {
  console.error(error);
});

> This avoids CORS issues entirely because Firebase SDK uses signed URLs under the hood.

#### Option 2: **Proxy the Request via Your Backend**

If you're stuck using `localhost:5173` during dev, and cannot upgrade from Spark plan, then:

– Create a small Laravel (or Node/Express) endpoint on your own backend
– That backend makes the Firebase request server-side (no CORS problem)
– Then responds to your frontend with the image or data

Example:

// Laravel controller
public function getImage()
{
    $url = 'https://firebasestorage.googleapis.com/...';
    return response()->stream(function () use ($url) {
        echo file_get_contents($url);
    }, 200, [
        'Content-Type' => 'image/png',
    ]);
}

#### Option 3: **Upgrade to Blaze Plan**
If you want full control (like setting CORS rules), you’ll need to switch to the **Blaze Plan (pay-as-you-go)** — but for many use cases, Option 1 or 2 will get you by just fine.

Would you prefer to stick with local dev, or are you open to trying Firebase Hosting for testing? I can help set either up quickly.

User
Normal recors save working
Just when try to save image the cors error showing
Assistant
Thanks! That clarifies it a lot.

### ✅ So the issue is:
– You're **saving regular (text) data to Firebase successfully**
– But **when uploading images to Firebase Storage**, you get the CORS error
– You're using **localhost:5173** during development
– You're on the **Spark (free) Firebase plan**

### 🔥 Cause:
When uploading images from the browser, Firebase Storage performs a **CORS preflight request** (`OPTIONS` request).
But on the Spark plan, you **can’t set custom CORS rules**, so the browser blocks that upload due to missing CORS headers.

### ✅ Solution: Use Firebase SDK for Uploads

If you **upload images using the Firebase JavaScript SDK**, Firebase handles CORS internally — even on the Spark plan. You **must not use direct XMLHttpRequests or fetch for file uploads**.

Here’s how to do it right:

### ✅ Upload Image with Firebase SDK (no CORS issues)

import { getStorage, ref, uploadBytes } from "firebase/storage";

// Initialize Firebase Storage
const storage = getStorage();

// Choose a file from an input element
const fileInput = document.getElementById("file");
fileInput.addEventListener("change", async (event) => {
  const file = event.target.files[0];
  const storageRef = ref(storage, 'portfolio/' + file.name);

  try {
    const snapshot = await uploadBytes(storageRef, file);
    console.log('Uploaded a file!', snapshot);
  } catch (error) {
    console.error("Upload error", error);
  }
});

### ✅ HTML

<input type="file" id="file" />

### ✅ Important:
– Make sure Firebase is initialized properly with your config
– Don’t use `fetch` or `axios` to call `firebasestorage.googleapis.com` directly for uploads — those will be blocked by CORS
– Use `uploadBytes()` or `uploadBytesResumable()` from the SDK

Would you like help integrating this with your current Vue or React setup? Let me know and I’ll tailor it for your framework.

User
Your data location has been set in a region that does not support no-cost Storage buckets. Create or import a Cloud Storage bucket to get started.
Assistant
Ah, this message gives us the **real root cause** now:

> **"Your data location has been set in a region that does not support no-cost Storage buckets."**

### 🚫 What's Happening

You're on the **Spark (free)** plan, and:
– You chose a region like **europe-west3**, **asia-south2**, etc.
– That region **does not support free Firebase Storage buckets**
– So, **Firebase Storage was never set up for your project**, even though the rest of Firebase (like Firestore or Realtime DB) works.

### ✅ Solution Options

#### **Option 1: Create a Firebase Storage Bucket in a Supported Region**

1. Go to **[Firebase Console](https://console.firebase.google.com/)**
2. Select your project
3. Go to **Build → Storage**
4. Click **"Get Started"**
5. If prompted, **select a supported region**, such as:
– `us-central1` ✅ (this one works for Spark plan)
– `us-east1`
– `europe-west1`
6. Click **“Done”** to create the bucket.

> ⚠️ Important: You can only create **one** Storage bucket per project on the Spark plan, and **you cannot change its location** later.

#### ❌ If the Region Is Already Set (and it's unsupported)

You will **not be able to use Firebase Storage** in that project on the Spark plan.

##### Two options then:
1. **Upgrade to Blaze plan** (pay-as-you-go) → unlock any region.
2. **Create a new Firebase project**:
– Choose **`us-central1`** when prompted to pick a region
– Enable Firebase Storage there
– Reconnect your frontend to the new project (update your `firebaseConfig`)

### ℹ️ To Check Your Current Bucket Region
– Go to [Google Cloud Console → Storage](https://console.cloud.google.com/storage)
– Check your bucket name and its **location**
– If it's **not set up**, then Firebase Storage isn't available in your current region

Let me know if you'd prefer to:
– Fix it by **switching projects**
– Or **upgrade to Blaze**
— I’ll guide you through either path step-by-step.

Leave a Comment

Your email address will not be published. Required fields are marked *