Problem: When you deploy a new version of your SPA, users with a tab open...
Problem:
When you deploy a new version of your SPA, users with a tab open will keep using the old SPA code.
Solution:
1. Specify the app version in each HTTP call from the UI via a x-app-version header.
2. Validate the x-app-version header on the API server. If x-app-version doesn't match the server's version, return an HTTP 400.
3. When the UI receives a 400 status code, tell the user to reload.
If you prefer, you can use HTTP 422 instead. It's more specific than a 400, and feels like a good fit for this use case.
And the header name can be whatever you like. Anything that starts with "x-" is a fine choice.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422
Many excellent suggestions in this thread.
Other good options:
1. You don't have to return an HTTP 400 and force the user to update their browser. The API can reply with a successful request instead (like an HTTP 205), or include an "x-stale-ui" header in the response to notify the UI that it's stale. Then the user can optionally click reload when/if they want to.
2. Consider periodically polling a simple "check version" API hosted on the UI's webserver instead. You can expose the package.json via this API. Especially useful if you don't have a dedicated backend API.
3. Consider using web sockets or server sent events to push a notification to the UI after a deploy instead.
4. You can use a service worker to notify the user when the UI is stale. For example, Vite's PWA plugin supports this.
5. Consider semver. You can force the user to refresh the UI immediately if it's truly critical (such as a major bug or breaking change), or make it optional otherwise.
Oops, I made a typo.
In the previous tweet I said "You can expose the package.json via this API."
Don't do that.
I meant to say "You can expose the package.json version via an API". Don't expose your entire package.json.
And here's an even simpler approach: Put the release version in index.html. This way, you can poll the server every x minutes to check if the version in index.html on the server is newer than the local version.