Set cache to files in Firebase Storage

Viewed 17795

I have a PWA running on Firebase. My image files are hosted on the Firebase Storage. I've noticed my browser doesn't save cache for files loaded from the storage system. The browser requests the files for every page refresh. It causes unnecessary delay and traffic.

Network stats

My JS script loads the files from the Firebase Storage's download link, example: https://firebasestorage.googleapis.com/v0/b/discipulado-7b14b.appspot.com/o/book3.png?alt=media&token=65b2cde7-c8a4-45da-a743-401759663c17.

Can I cache those requests?

UPDATE

According to these answer I shouldn't use Firebase Storage to host files from my site. Just to manage downloads and uploads from users. Is this correct?

6 Answers

Putting the pieces together for any future references here

First,

// Create file metadata to update
var newMetadata = {
  cacheControl: 'public,max-age=4000',
}

Then,

storageRef.put(file, newMetadata)

Also, Is possible to change the cache control of an existent resource accessing Google Cloud Console. (So, don't need to reupload with the cache metadata)

Access the console and go to 'Cloud Storage'. Browse to your bucket and file, where you find 'edit metadata'.

Here, you can put the cache control policy:

Edit metadata for object

Use Serviceworker for that.

You can save the urls without the token in cache and fetch them later.

This way changes in tokens will not affect you caching.

To cache without token, use something like

cacheUrl = url.origin + url.pathname.substr(0, url.pathname.length - urlPath.length) + urlPath;

and then cache.put(cacheUrl, response);

Related