· 1 min read
Adding Cache Headers to Firebase Hosting
This is a note to self about setting the caching rules for Firebase hosting but hopefully you will find it useful too.
The problem
When building PWAs, one of the requirements is to include a service worker. Service workers are background scripts that can be used to intercept fetch requests and respond with cached resources, amongst other things. It is best practice that they are not cached by the browser, otherwise it is possible to get into a situation where the client never gets a copy of resources as they get updated.
The Solution
When you initialise a new firebase project using the Firebase CLI, it generates a few useful files for you. One of these is the firebase.json file which holds much of the projects configuration. We can update this file to include a 'headers' property. This will allow us to apply cache-control to resources. It takes an array of header rules containing a source on which to apply the rule, and the key value pair that defines the header.
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/service-worker.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
}
]
},
"storage": {
"rules": "storage.rules"
}
}
Conclusion
This simple configuration is all you need. When you deploy your application to Firebase hosting, the service-worker.js file will be served with a no-cache header instructing the browser to make sure it has the most recent version of the resource each time. No more worrying about out service workers being cached and unintended repercussions.