I need to design a way to notify my user the SPA has updated if they don't refresh their browsers, i.e. if no requests to get index.html
is made after the initial load, how do I notify users the javascript or css files have updated on the server? Note, it is not the REST api that my SPA communicate with updates but the SPA's static resources.
I think the options are limited:
- Start a time to keep querying the latest version number
- Add a customer header field about the latest version in responses for most if not all XHR requests SPA send
- using websocket to notify SPA
- I am not familiar with service worker but I read articles about it may work too.
There is another problem I need to deal with, my SPA is deployed on its own server, which is separated from the REST server it communicates with(although I suspect it is common) and there are cases that the SPA has new versions while REST server doesn't. The version number I design should be able to tell these 2 cases.
I notice folks asked this kind of questions on stackoverflow many times. I can find more 10 questions, with the earliest one I found in 2013 and the latest one in 2019. I list some here.
- How to handle expired files without refreshing the browser when using Single Page Application (SPA)?
- How to force update Single Page Application (SPA) pages?
- How can I force SPA clients to hard refresh if there is a new build?
- Refreshing a cached Angular SPA
- Proper way to refresh Single Page Application
The reasons I asked here are:
- I like to design a build process to update the SPA version automatically. Manually update the version number is error prone. None of answers seem to address this.
- All those Q&A on SO seemed to failed to mention the case that the SPA server and REST server is separated and what I need here is an update for SPA files. For example if I use the option 2, adding a customer header field in response I need to differentiate the SPA version and REST api version. None of the answers I saw address this. Some answers just focus on REST api version update.
- I believe this question should be address by a build process, a communication process and maybe a deploy model. So this is a question about SPA architecture.
- The mere facts that this question has been asked so many times for 8 years probably has said it clearly that there is no easy answer for it, probably even without some best practices. Some answers failed to realize is the core issue here is to retrieve
index.html
so focus on cache busting, file naming or settingCache-Control
, like this one How to force the browser to reload cached CSS and JavaScript files or the question answered here Dealing with browser cache in single-page apps. That was not my problem because my SPA is hosted on nginx server with etag on. As long as users hit F5 my problem is solved.