bug: “cannot bind to undefined” error in SSR

Bug Report

Ionic version:
[ ] 4.x
[x] 5.x

Current behavior:
When running the app with SSR you get error in the console window:

TypeError: Cannot read property 'bind' of undefined
    at hydrateFactory (...\dist\app\server\main.js:169296:36)
    at render (...\dist\app\server\main.js:196485:9)
    at ...\dist\app\server\main.js:196417:62
    at new ZoneAwarePromise (...\dist\app\server\main.js:441505:33)
    at hydrateDocument (...\dist\app\server\main.js:196409:33)
...

This error produce app in the SSR but without Ionic components hydrated into the code. This is visible when you disable JavaScript to test app.

Expected behavior:
Application in the SSR should generate without this error and should have Ionic components hydrated even if JavaScript is disabled.

Steps to reproduce:
Please run Ionic – Side-Menu or Tabs starter template app in SSR with latest ionic-angular (v. >= 5.4.2). Then start npm run dev:ssr. After that visit page at http://localhost:4200 you will get this error.

Related code:
This error didn’t show in Ionic versions < 5.4.2. The problem is in the hydrateFactory function on the server side code and this cause the problem with rendering of the Ionic components. You may find this function in node_modules/@ionic/core/hydrate/index.js

function hydrateFactory($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve) {
...
var fetch = $stencilWindow.fetch.bind($stencilWindow);
...
}

This error means that $stencilWindow.fetch is undefined.

Other information:
The simple solution is to comment this line and the app in SSR start working as expected – Ionic components are hydrated without any problems with JavaScript disabled.

Ionic info:

Ionic:

   Ionic CLI                     : 6.12.3
   Ionic Framework               : @ionic/angular 5.5.2
   @angular-devkit/build-angular : 0.901.12
   @angular-devkit/schematics    : 9.1.12
   @angular/cli                  : 9.1.12
   @ionic/angular-toolkit        : 2.3.3

Cordova:

   Cordova CLI       : not installed
   Cordova Platforms : android 8.1.0, electron 2.0.0
   Cordova Plugins   : not available

Utility:

   cordova-res : not installed
   native-run  : not installed

System:

   Android SDK Tools : 26.1.1 (c:\Users\signu\AppData\Local\Android\android-sdk)
   NodeJS            : v14.15.3 (C:\Program Files\nodejs\node.exe)
   npm               : 6.14.9
   OS                : Windows 10

1 possible answer(s) on “bug: “cannot bind to undefined” error in SSR