I have come to the conclusion that my SPA using reactJS coupled with react router (react-router-dom 5
, a client side routing service) CAN ONLY get a newly deployed javascript file IF IT is through a refresh. There is no other way. Am I wrong?
Scenario:
- User is on the homepage
- A new JS bundle gets deployed. (I am using webpack and using the following format:
app.[hash].js
as per webpacks's caching documentation. This is then referenced by index.html e.g.<script src="app.dc1abe70ccbf1b703e01.js">
) - User now clicks on another link (new route) BUT the old JS still shows (even though there is new code available)
- Only when a user does a refresh of the page, does the new code show. (Http status 200 and then 304 on each subsequent refresh until JS changes again which will result in another 200 and so on)
Now, I have gone though several threads, but I am still not clear on how to implement a simple solution to get a freshly deployed JS file WITHOUT a refresh from the back end for an SPA (ReactJS) using react router that replaces a cached version of the JS file between requests.
My understanding
When you use react router, a route is loaded within the SPA when clicked (client side) without requesting any html or js from the back end because there is no need to. i.e. the loading is instant because it's meant to be an SPA. This makes sense because as I said, when the app is loaded the first time, app.[hash].js
is downloaded and subsequently referenced.
I have seen many other threads offering various solutions like:
- forcing the server to issue a new JS file:
script.js?v=1
This however is a hack and you will end up with multiple versions of js files in your browser as per this. Besides, I am using routes (essentially, links managed through react router). I thinkscript.js?v=1
is for individual links. I am also using webpacks format for my js references:app.[hash].js
- Others have asked the same question regarding caching and SPA's but never received replies like here and here
Conclusion and goal
According to this comment: This is expected behaviour and until user will not refreshes his page, new changes will not be loaded – Zohaib Ijaz Apr 13 at 14:02
from this thread
MOSTLY everything I have researched does not speak specifically to ReactJS PLUS react-router-dom. They mention versioning js files with a ?ver=xyz
but that is for individual links I believe, NOT a router with routes. Some others mention using app.[hash].js
but then stop short to explaining what to do next.
EVERYTHING I have researched leads me to believe that in order to see new JS changes the next time a react router link is clicked, my ReactJS SPA with react-router can only see these new changes if it is refreshed. And if so, then there is NO SOLUTION but to hope the customer will refresh the page (because this IS the practical solution)?
p.s I am using express server