CORS on firebase storage
Asked Answered
S

4

9

I'm gettin the normal cors error on my firebase storage when I do a get call on an html file:

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I'm using axios for the call:

axios.get('https://firebasestorage.googleapis.com/v0/b/xxxxx-xxxxx.appspot.com/o/files%2Fsigning%2F148%2F459.html?alt=media&token=f3be2ef2-a598-4c30-a77b-8077e8b1f7bc',
{
   headers: {'Access-Control-Allow-Origin': '*',}
)

I have the access set to public:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

This same setup works fine when I load images but it's giving me the error for the stored html file. Any thoughts on how to fix it?

Storage answered 12/12, 2017 at 8:26 Comment(6)
Remove "headers: {'Access-Control-Allow-Origin': '*',}" from your frontend code. That’s what’s triggering your browser to send a preflight request. The Access-Control-Allow-Origin is strictly a response header for servers to send back. You never want to add it to a request.Dulce
That was one of my attempts to bypass the problem. It's the same with or without it.Storage
Without it, exactly what error do you get? It must be something other than “Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response”.Dulce
This is the full error: Failed to load firebasestorage.googleapis.com/v0/b/xxxx-xxxx.appspot.com/o/…: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:3000' is therefore not allowed access.Storage
You need to set CORS config on the server side, which I think you can do using the gsutil tool. For an example, see the answer at #43109827. Or just go straight to the docs at cloud.google.com/storage/docs/…Dulce
Correct. I think I just fixed the problem. Going to post it here for others who might run into the same problem.Storage
S
32

Firebase is using the same storage infrastructure as google cloud and even though there is no firebase method to set the cors rules, you can use gc set up. First you need to install google cloud sdk:

curl https://sdk.cloud.google.com | bash

Restart your shell:

exec -l $SHELL

Initialize gcloud. This will ask you to select your account and authenticate.

gcloud init

Then create a json file with the following content

[
    {
      "origin": ["http://example.appspot.com"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD", "DELETE"],
      "maxAgeSeconds": 3600
    }
]

And run this with your firebase storage gc: endpoint

gsutil cors set yourFile.json gs://yourProject

That should fixe the problem for you as well.

Storage answered 12/12, 2017 at 18:33 Comment(1)
Thank you very much @Adam Boostani. it workedTobolsk
S
1

Answer of mister Adam Boostani did work after I change the json file code line from :

https://firebase.google.com/docs/storage/web/download-files#cors_configuration

Firebase is using the same storage infrastructure as google cloud and even though there is no firebase method to set the cors rules, you can use gc set up. First you need to install google cloud sdk:

curl https://sdk.cloud.google.com | bash

Restart your shell:

exec -l $SHELL

Initialize gcloud. This will ask you to select your account and authenticate.

gcloud init

Then create a json file with the following content

[
    {
      "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
    }
]

And run this with your firebase storage gc: endpoint

gsutil cors set yourFile.json gs://yourProject

That should fixe the problem for you as well. it fixed it Thank you Mister Adam Boostani

Sackett answered 17/5, 2023 at 9:41 Comment(0)
M
0

After init the application you need to use setCorsConfiguration method

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The origin for this CORS config to allow requests from
// const origin = 'http://example.appspot.com';

// The response header to share across origins
// const responseHeader = 'Content-Type';

// The maximum amount of time the browser can make requests before it must
// repeat preflighted requests
// const maxAgeSeconds = 3600;

// The name of the method
// See the HttpMethod documentation for other HTTP methods available:
// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethod
// const method = 'GET';

async function configureBucketCors() {
  await storage.bucket(bucketName).setCorsConfiguration([
    {
      maxAgeSeconds,
      method: [method],
      origin: [origin],
      responseHeader: [responseHeader],
    },
  ]);

  console.log(`Bucket ${bucketName} was updated with a CORS config
      to allow ${method} requests from ${origin} sharing 
      ${responseHeader} responses across origins`);
}

configureBucketCors().catch(console.error);

This is my example with NestJs

import { ConfigService } from '@nestjs/config';
import * as admin from 'firebase-admin';

const configureBucketCors = async (app) => {
  const configService: ConfigService = app.get(ConfigService);

  return admin
    .storage()
    .bucket(configService.get<string>('BUCKET_NAME'))
    .setCorsConfiguration([
      {
        origin: ['http://localhost:3000'],
        responseHeader: ['Content-Type'],
        method: ['GET', 'HEAD', 'DELETE'],
        maxAgeSeconds: 3600,
      },
    ]);
};

export default async (app) => {
  const configService: ConfigService = app.get(ConfigService);
  await admin.initializeApp({
    databaseURL: configService.get<string>('FIREBASE_DATABASE_URL'),
    storageBucket: configService.get<string>('BUCKET_NAME'),
  });

  await configureBucketCors(app);
};

Check the docs for more details https://cloud.google.com/storage/docs/cross-origin

https://cloud.google.com/storage/docs/configuring-cors#storage_cors_configuration-nodejs

Mottle answered 15/11, 2021 at 15:57 Comment(0)
S
0

Initialize gcloud. Once you run below command it will ask to authenticate. Choose the gmail account in which the project is present. Select the appropriate firebase project.

gcloud init

Next create a json with below content, Make sure to keep the origin as * to allow any url or put the domain url

[
    {
      "origin": ["*"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD", "DELETE"],
      "maxAgeSeconds": 3600
    }
]

Next run the firebase storage bucket name. Go to firebase storage and copy the firebase storage bucket name and substitute in the below command

gsutil cors set yourFile.json gs://<storage-bucket-name>
Strychninism answered 29/10, 2023 at 10:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.