Back to Blog

In this blog post, I want to talk about CORS and how to configure it for Firebase Storage.

About CORS

CORS stands for Cross-Origin Resource Sharing. Simply put it’s a mechanism that tells the server which domain has access and can load contents from the server. If you want to read more about it here is a good article: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.

Why would this matter?

Let's say you upload an image to firebase storage using the firebase console. Then you will not have any issue, because the origin is the same. But if you upload an image from a Flutter app (Mobile/Web) and try to load the image in the web app you will get an “image codec error”. This is because the upload is from a different origin. The easy fix for this would be to use Flutter’s HTML renderer instead of Canvaskit. But you might not want to use this all the time.

The Fix

The fix for this issue is pretty simple. We need to create a “JSON” file via the Google cloud console.

  • Go to this link: https://console.cloud.google.com/ and select the project you want to configure CORS for
  • Click the active cloud shell icon on the top right
  • It will open the terminal for you. This will take some time because it will have to create a connection. While loading you will see a button on the right called Open Editor. Go ahead and click that. You will see something similar to the image below
  • Click File -> New file and name the file as cors.json. Inside the file paste the code below and save the file.
  • 1[
    2  {
    3    "origin": ["*"],
    4    "method": ["GET"],
    5    "maxAgeSeconds": 3600
    6  }
    7]
    8

    Let's look into the code and understand what each of them does.- Origin: List of URLs that can load contents. We use “*” so any website/URL will have access- Method: We tell our server what we want to perform. In this case, we want to get the files, hence our method is “Get”- maxAgeSeconds: This tells our server how long it should wait before it needs to repeat a request we have put it as “3600”To read more about configuration follow this link: https://cloud.google.com/storage/docs/configuring-cors#gsutil

    5. Now click the Open terminal button on the right and paste the following command“gsutil cors set cors.json gs://your-bucket”gs://your-bucket is the URL of your storage bucket which you can get from the Firebase Console.

    Once you have run the command CORS will be successfully enabled for your project.

    You will see a message on the console like “Setting CORS on gs://your-bucket”, where your bucket is the storage bucket you enabled cors for.

    and when you try loading images using Canvaskit renderer you won’t have any issues.

    This blog post was inspired by a StackOverflow thread which can be found over here: https://stackoverflow.com/questions/37760695/firebase-storage-and-access-control-allow-origin/37765371.