angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

index.html formatting breaks Universal SSR

Open dottodot opened this issue 8 years ago • 49 comments

Versions

Angular CLI: 1.6.1
Node: 8.9.1
OS: darwin x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router
... service-worker

@angular/cli: 1.6.1
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.1
@schematics/angular: 0.1.11
typescript: 2.4.2
webpack-bundle-analyzer: 2.9.1
webpack: 3.10.0

Repro steps

Build the app

Observed behavior

After building the app and starting the express app and I can see I not getting SSR content. However if I open the compiled index.html and save it it Visual Code so that the html is formatted again the problem goes away. This suggests that the build process is somehow formatting the html in a way that's causing the issue, but I don't get any errors.

Also the other odd thing is if I removed the Service Worker I don't get the issue so I initially though that was the problem as reported here https://github.com/angular/angular/issues/20890

Desired behavior

Be able to include build app and have SSR.

I'm just very confused as to how the combination of the formatted html and service worker can be preventing ssr working.

Mention any other details that might be useful (optional)

I've tried removing all additions to my index.html to make sure nothing I've added causes the issue. I've only recently started having this issue but can't be sure of which version.

dottodot avatar Dec 14 '17 11:12 dottodot

@alxhub read some discussion in this thread which is closed, However, I am having similar issue as described here. On first SSR load i get complete html (below)

first-load-html.txt

Subsequent page loads are cached: image

But the html is trimmed down. (below): trimmed-html.txt

This is ngsw.json after build. ngsw.json.txt

Here is another important question, if server rendered pages are loaded from server, then should these pages be cached by service worker? Any best practice of caching SSR documents in the context of service worker?

asadsahi avatar Dec 15 '17 18:12 asadsahi

Yes that was my issue that I posted in the main angular repo, not sure why it was closed without any explanation. Anyway after that I then discovered that I can get both ssr and service worker working together simply by reformatting the generated index.html, which is why I've posted in cli as wondering if something in the build process is causing the issue.

So after building my app my index.html looks like

<!doctype html><html lang="en"><head><meta charset="utf-8"><title></title><base href="/"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" type="image/x-icon" href="/favicon.ico"><link rel="manifest" href="./manifest.json"><meta name="theme-color" content="#3e3935"></head><body><bos-root class="site"></bos-root><script type="text/javascript" src="inline.f6b500976c47223e609b.bundle.js"></script><script type="text/javascript" src="polyfills.948979b9d906d248bcd3.bundle.js"></script><script type="text/javascript" src="main.421aaf9b0deca09e5fdd.bundle.js"></script></body></html>

and I don't get any ssr with a service worker, but if I format that index.html to

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title></title>
    <base href="/">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="manifest" href="./manifest.json">
    <meta name="theme-color" content="#3e3935">
</head>

<body>
    <bos-root class="site"></bos-root>
    <script type="text/javascript" src="inline.f6b500976c47223e609b.bundle.js"></script>
    <script type="text/javascript" src="polyfills.948979b9d906d248bcd3.bundle.js"></script>
    <script type="text/javascript" src="main.421aaf9b0deca09e5fdd.bundle.js"></script>
</body>

</html>

my service worker works and so does ssr. I just can't understand why that would be. I absolutely mystified as the only difference is one is minified html.

dottodot avatar Dec 15 '17 19:12 dottodot

@dottodot what you have shown seems to be the prod build index.html. which doesn't look like and SSR generated source.

If you look at the first file I sent above that has alot of source come from SSR and after service worker caches that source, it caches trimmed version, which is issue in my case.

I am also not sure if it is a good idea to cache index.html with service worker if we are using SSR since each url might have different source rendered from server and there might now be much gain we get from performance standpoint by caching index.html if it is SSR rendered already.

asadsahi avatar Dec 16 '17 00:12 asadsahi

@asadsahi yes it is the prod build index.html. My point was that if I format that generated index.html as I've shown the problem goes away. Also removing the index.html from the service worker also resolves my issue, so maybe the best approach is to not cache the index.html at least until someone can confirm if this is a bug or if index.html just shouldn't be included when using a service worker with universal.

dottodot avatar Dec 16 '17 08:12 dottodot

@dottodot what is confusing me is that you are stating your problem with html file which doesn't look like SSR generated source

This source has app component selector, but I am expecting if this is SSR source this should be the pre-rendererd output instead.

Note: This is not ssr source.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title></title>
    <base href="/">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="manifest" href="./manifest.json">
    <meta name="theme-color" content="#3e3935">
</head>

<body>
    <bos-root class="site"></bos-root>
    <script type="text/javascript" src="inline.f6b500976c47223e609b.bundle.js"></script>
    <script type="text/javascript" src="polyfills.948979b9d906d248bcd3.bundle.js"></script>
    <script type="text/javascript" src="main.421aaf9b0deca09e5fdd.bundle.js"></script>
</body>

</html>

Therefore, if you are saying you are having problem with service worker in the context of SSR then what service worker should cache is whatever server sent to client. If SSR, it should be final output of the page, if it is non-ssr then it should be source above.

asadsahi avatar Dec 16 '17 12:12 asadsahi

Yes I know, I'm trying to explain what I think is causing SSR to not work, which I believe is the index.html file, this is why posting the contents of the generated file not ssr generated source.

If you forget about the html I've posted, it's a simple as with the index.html included in the service worker ssr doesn't work. If I've remove the index.html from the service worker ssr works.

dottodot avatar Dec 16 '17 12:12 dottodot

Right, So the very first time you get source from server is SSR generated source (i.e before service worker caches it)? If that is the case then it surely is something wrong with how Service worker caches that page.

Original question still begs some explanation from some expert, "Whether we should cache SSR page in service worker?" :)

asadsahi avatar Dec 16 '17 12:12 asadsahi

Hi @dottodot

I don't see a reproduction for your issue. Could you provide a github repo we could clone and look at? It should contain the smallest amount of code (as close as a new app) as possible.

Thanks!

hansl avatar Dec 18 '17 17:12 hansl

@hansl unfortunately I've been unable to replicate in a new app, so probably something particular to my setup. Trouble is as there is no errors so it could be anything and not sure how I can narrow it down.

dottodot avatar Dec 18 '17 19:12 dottodot

@hansl would you be able to comment on question I have asked here?

asadsahi avatar Dec 18 '17 21:12 asadsahi

@dottodot : Experiencing the same issue. I have enabled Service worker and Angular universal but however when viewing the view source only angular tags are there.

As you stated when i format the index.html , this seems to be perfectly working. Very Strange ! I thought i am the one Experiencing the weird issue. I am using @angular/cli Version 1.6.1.

Have you solved it?

ssatz avatar Dec 22 '17 14:12 ssatz

@ssatz Unfortunately not, I suspect there will be more as there is no error and you only find out when you check the view source.

dottodot avatar Dec 22 '17 16:12 dottodot

Hello All, Please find the repository to reproduce the bug. https://github.com/ssatz/Angular-SSR-Service-Worker

Build SSR using NPM and view the view source.

ssatz avatar Dec 27 '17 08:12 ssatz

Yeah I’ve found the same When visiting my app without the service worker, installed, I’m seeing the SSR instead of the built index.html, as expected. The service worker then gets installed by the browser. I then revisit my app and now when I view source it’s the SPA build of index.html not the SSR.

My gut instinct is telling me that during the build possibly, the SPA version of index.html is getting packaged into the js, and that the service worker is caching that, instead of caching the SSR html.

My expectation would be that the SSR html would be cached in the SW.

jimdrury avatar Jan 07 '18 00:01 jimdrury

Same issue here. Any news about that? I've removed index.html from the SW cache in the meanwhile in order to get SSR.

kaikcreator avatar Apr 06 '18 17:04 kaikcreator

I am guessing removing index.html will remove offline capability from PWAs since index file isn't cached anymore.

asadsahi avatar Apr 06 '18 18:04 asadsahi

Yes, you're right. But if I don't remove index.html from cache, then SSR doesn't work. I've trying by formatting the index.html file as suggested by @dottodot and @ssatz, but in my case it doesn't work neither.

Until this issue is fixed, there's no win-win solution here: Or I lose offline capabilities, or I lose SSR capabilities :(

kaikcreator avatar Apr 08 '18 21:04 kaikcreator

I have the same issue... Any news ?

quen2404 avatar Apr 26 '18 08:04 quen2404

Hey guys,

after investigating some hours, i want to share my results. (feel free to correct me if im wrong)

my setup:
angular cli 6.0.1

  • service worker
  • ssr (angular universal)
  • i used the smallest setup for ngsw-config.json
{
  "index": "/index.html",
  "assetGroups": [{
    "name": "app",
    "installMode": "prefetch",
    "resources": {
      "files": [
        "/favicon.ico",
        "/index.html",
        "/manifest.json",
        "/*.css",
        "/*.js"
      ]
    }
  }, {
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {
      "files": [
        "/assets/**"
      ]
    }
  }]
}

FYI: i think formatting the index.html is not the reason why the ssr, etc. doesnt work as expected.

How it works under the hood:

Navigate to the site for the first time: (i.e.: http://localhost:4200) this response is the SSR rendered version of the index.html. (so far so good) the SSR rendered index.html will be shown.

the service worker gets installed, and starts to load the resources (in the meantime) (def. in ngsw-config.json) in our example the index.html. -> this index.html will be cached. (if the site gets reloaded or you are offline, the serviceworker will return this index.html. Thats what we expect).

after analysing the network traffic, i saw that the index.html (resource) which is loaded by the service worker is never prerendered. so i watched the server code (here is the important part)

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});

in our case when the serviceworker loads the index.html he the server route for returning the static file from our dist/browser folder is used. its like calling http://localhost:4200/index.html which means the cached index.html is never ssr. its always the static file from our dist/browser folder.

After reloading the site the service worker will return the cached index.html and thats it. using an app-shell would help in that case. bec. the app-shell is compiled and added in our static index.html. (maybe thats a solution for some of you), but in my case i definitly want to use ssr.

i tried to modify the server source, to return also a rendered version of the index.html. instead of returning the static version. I added

app.get('/index.html', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});
....
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

before the static file path. Now the result was as expected. The first call worked (ssr page). service worker loaded the prerendered index.html. (that looked perfect)

sadly there was the next problem incoming: when i tried turned the network off. the site was not working anymore. (but thats one of the most important things for my case)

to figure out why took me quite a while.

the problem here was: the serviceworker loaded the ssr index.html. but if you take a look at angular-cli dist folder (there is a file ngsw.json) which contains a hashtable for all static resources. like our index.html and this hash is based on the static file in the dist folder.

if we return an ssr index.html -> its content look different (obvi.) that results in a different hash. but the service-worker compares the hash from the ngsw.json hashtable and the response (index.html) if its hashes doesnt match he will do another call index.html?ngsw-cache-bust (to load the index.html again) and if this hash is also different (which is obvi.) the index.html will never get cached.

-> and thats the crux here. a solution would be:

  • manipulating the server.ts as i did. to return a ssr index.html version
  • and removing the index.html hash from ngsw.json (but this file is generated and i didnt found a proper solution todo this (not sure if its a good idea todo this) that looks like a dirty workaround, but it should work)

Resumee: (but thats only my personal opinion)

SSR combined with PWA is actually only worth for the first initial call of the site. -> bec. its fast and got prerendered. After reloading, the SSR has absolutly no effect. except you want to implement the solution above.

Whats also important to keep in mind. if you are using a proxy you have to disable the caching for the index.html -> otherwise ssr will not work (or if you you render with user specific content, it will be a security problem... cached user specific data...)

Sorry for such a long post, but i didnt found a good answer searching the web. Maybe it helped someone. (if anything is not clear feel free to contact me)

Priemar avatar May 17 '18 15:05 Priemar

thanks,now ssr and service worker both are working.But in offline it shows network disconnected error while navigating to other routes and refreshing the page

kamalakkanni avatar May 21 '18 06:05 kamalakkanni