JSON Upload and Download to Local Storage — Firebase.

Derrick Sekidde
Crane Cloud
Published in
4 min readMar 1, 2023

--

Last week, I had a dilemma on how to upload and download JSON data to firebase. The system design required that the data on Firebase be stored in JSON files that had a cron job that periodically synced for more complex functionality on the admin side but for a regular user, I wanted them to just be able to upload and download at ease with downloading having an abstracted functionality of picking the local storage object and converting it into a JSON file and downloading doing the reverse.

Uploading and downloading JSON files to and from Firebase can be a useful feature for many web applications lately. With it allowing for easy data storage, management, and sharing. In the next paragraphs, I detail as we explore the process of doing exactly that.

Firebase is a popular mobile and web application development platform owned by Google. It offers a variety of services such as real-time database, authentication, storage, and hosting. Firebase Storage is one of the services offered by Firebase that allows users to store and retrieve files in the cloud. It can be used to store various types of files, including JSON files — which is our focus today.

To upload a JSON file to Firebase Storage, I had to first convert the JavaScript object into a Blob. A Blob is a binary representation of data that can be used to store files. We can create a Blob from a JavaScript object using the Blob constructor. The constructor takes an array of values and an options object as parameters. We can set the type of the Blob to “application/json” to indicate that it is a JSON file.

Once we have created the Blob, we can use the File constructor to create an actual file. The constructor takes the Blob and a file name as parameters. We can then use the put method of the Firebase Storage reference to upload the file to the storage bucket. The put method takes the file and an optional metadata object as parameters.

Here is an example code snippet that demonstrates how to upload a JSON file to Firebase Storage:

var filename = jsonFileName + '.json';
// Get the JSON string and parse it into an object
var userObject = JSON.parse(localStorage.getItem("user"));

// Create a new Blob object with the JSON string as content
const blob = new Blob([userJSON], { type: "application/json" });

let storageRef = firebase.storage().ref("json/" + filename);
let uploadTask = storageRef.put(blob);

In the above code, we first pick a JavaScript object from local storage. We then create a Blob from the object using the JSON.stringify method. We pass the Blob and the file name to the File constructor to create the file. We then create a Firebase Storage reference and use the put method to upload the file to the storage bucket.

To download a JSON file from Firebase Storage, we can use the getDownloadURL method of the storage reference. The method returns a Promise that resolves with the download URL of the file. We can then use the fetch API to download the file from the URL. Once we have the file content, we can parse it into a JavaScript object using the JSON.parse method.

Here is an example code snippet that demonstrates how to download a JSON file from Firebase Storage:

const storageRef = firebase.storage().ref().child("data.json");
storageRef.getDownloadURL()
.then(url => fetch(url))
.then(response => response.json())
.then(data => localStorage.setItem("data", JSON.stringify(data)));

In the above code, we first create a Firebase Storage reference to the file we want to download. We then use the getDownloadURL method to get the download URL of the file. We use the fetch API to download the file from the URL. Once we have the file content, we parse it into a JavaScript object using the JSON.parse method. Finally, we store the object in local storage using the setItem method.

However, there is a known issue with downloading JSON files from Firebase Storage. When we try to download a JSON file directly from the Firebase Storage URL, we may get a CORS (Cross-Origin Resource Sharing) error. This is because Firebase Storage restricts direct access to files from domains other than firebaseapp.com. To mitigate this issue, we need to set the CORS configuration for the Firebase Storage bucket.

To set the CORS configuration for the Firebase Storage bucket, we can use the gsutil tool provided by Google Cloud SDK. Setting up the tool locally can be done using this documentation.

I created a filed locally called cors.json and added this as its contents. This configuration allows GET requests from any domain for up to one hour.

[    
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
gsutil cors set cors.json gs://[BUCKET_NAME]

Replace [BUCKET_NAME] with the name of your Firebase Storage bucket. With the CORS configuration set, we can now download the JSON file from Firebase Storage without getting a CORS error.

--

--