Up-to-date answer (v11.0.0)
Angular now has a navigationRequestStrategy
option which allows to prioritize server requests for navigation. Extract of the changelog:
service-worker: add the option to prefer network for navigation
requests (#38565) (a206852), closes #38194
To be used wisely! This warning appears in the documentation:
The freshness
strategy usually results in more requests sent to the
server, which can increase response latency. It is recommended that
you use the default performance strategy whenever possible.
Old answer (for archaeological purposes)
I have found a working solution, the navigationUrls
property of ngsw-config.json
contains a list of navigation URLs included or excluded (with an exclamation mark) like explained in the documentation.
Then I configured it like this:
"navigationUrls": [
"!/**"
]
This way, none of the URLs redirect to index.html
and the server-side rendered app comes into play when the app is first requested (or refreshed), whatever the URL is.
To go further, the three kinds of URLs managed by the service worker are:
- Non-navigation URLs: static files cached by the service worker and listed in the generated
ngsw.json
file with their corresponding hashes
- Navigation URLs: redirected to
index.html
by default, forwarded to the server if the "!/**"
configuration is used
GET
requests to the backend: forwarded to the backend
In order to distinguish a GET
XMLHttpRequest
from a navigation request, the service worker uses the Request.mode property and the Accept
header that contains text/html
when navigating and application/json, text/plain, */*
when requesting the backend.
Edit: This is actually not a good practice to do that for two reasons:
- Depending on the network quality, there is no guarantee that the server-side version will render faster than the cached browser version
- It breaks the "update in background" mechanism. Indeed, the server-side rendered app will always refer to the latest versions of the JavaScript files
For more details on this, please take a look at the Angular's team member answer to my feature request: https://github.com/angular/angular/issues/30861