Search code examples
javascriptreactjsgoogle-cloud-platformcreate-react-appfirebase-hosting

How to use React Code Splitting and Firebase Hosting without ChunkLoadError


I need to use React Codes Splitting with a Create React App, hosted on Firebase Hosting.

However, I have a problem, because Firebase Hosting only hosts the latest version of any app. This means that if you deploy a new app version (N+1), and a user has the existing version open (N), and that user crosses a code splitting boundary, they will request a old chunk (N), which is no longer hosted in Firebase Hosting, because the current version has changed (N+1).

So, how does one avoid Code Splitting ChunkLoadErrors in Firebase Hosting? Is there a way to tell Firebase Hosting to retain all prior versions you've deployed, and only add the new files from the latest release (e.g. index.html and the JS/CSS chunks?).


Solution

  • I fixed this using the following process:

    1. Push files for each new release to a bucket, like gs://my-buck/app/releases/<git-sha>/
    2. Make a release folder locally, like firebase_deploy/
    3. Identify the last N release tags in the git history
    4. For each old release, gsutil -m -q rsync -rc gs://my-buck/app/releases/<git-sha>/ firebase_deploy/ to copy old files down
    5. Copy the new release files rsync -rvc build/ firebase_deploy/
    6. Deploy the app to Firebase from firebase_deploy/, with your new and old chunks, giving preference to the new chunks where any conflict might occur.

    This process eliminated the ChunkLoadErrors for me.

    Note: Use a bounded N prior releases, so you don't run up your Firebase Hosting storage bill. If you don't have many artifacts, you could possibly retain all previous releases, if you wanted.