Marks Polakovs
Marks Polakovs

Reputation: 508

Not including old JS in Firebase hosting causes service worker white screen

The build process of create-react-app (yarn run build) deletes the old static JS file before building anew. When deployed to Firebase Hosting, the old JS files are not included and are no longer served.

However after visiting the old version the Service Worker (built by sw-precache and sw-precache-webpack-plugin, included by default in CRA) has cached the old HTML, which includes the old JS file, which is no longer served, so I get a white screen and an error in the console, which is only fixed by clearing cache and reloading.

Am I doing something wrong?

Upvotes: 3

Views: 804

Answers (2)

James Britton
James Britton

Reputation: 412

I resolved this slightly differently to Marks answer.

Within your firebase.json file you need to make sure the Service Worker and the index.html file aren't cached. For me it was the index.html being cached which was the main issue.

Webpack changes the chunks name with each build and removes the previous version from /build. Therefore when they don't get uploaded and your browser looks at the cached index.html file it causes the white screen and the error.

I ended up with the following in my firebase.json file. Hope that helps

{
  "hosting": {
    "public": "build",
    "headers": [
      {
        "source": "/service-worker.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-store"
          }
        ]
      },
      {
        "source": "/index.html",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-store"
          }
        ]
      }
    ],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ],
    "source": "functions"
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  }
}

Upvotes: 3

Marks Polakovs
Marks Polakovs

Reputation: 508

The issue was that my Cache-Control headers were too short, meaning that my JS file wasn't being cached for long enough, causing the browser to re-request it upon a reload and not find it until the Service Worker updates.

Resolution: have long Cache-Control headers

Upvotes: 2

Related Questions