Ionic angular server side rendering showing to many errors

My whole IONIC project uploaded on Github https://github.com/yashdabi/ionic-angular-ssr

following some tutorials like this below https://ionicframework.com/blog/ssr-with-angular-universal-and-ionic/ but to many errors are showing after “npm run serve:ssr” and I am not able to resolve these errors

  1. window is not defined
  2. self is not defined
  3. Error:NotYetImplemented
  4. Cannot redefine property: constructor
  5. win.matchmedia is not a function
ReferenceError: self is not defined
    at Object.QdDj (F:\ionic4-project\learn-project\ionicPWA\dist\server\dom-js.js:45:9)
    at __webpack_require__ (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:26:30)
    at __webpack_require__.t (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:83:33)
    at ZoneDelegate.invoke (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:579:26)
    at Object.onInvoke (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:72557:33)
    at ZoneDelegate.invoke (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:578:52)
    at Zone.run (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:338:43)
    at F:\ionic4-project\learn-project\ionicPWA\dist\server.js:1098:34
    at ZoneDelegate.invokeTask (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:611:31)
    at Object.onInvokeTask (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:72538:33)
Error: NotYetImplemented
    at Document.exports.nyi (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:69823:9)
    at bootstrapLazy (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:89424:68)
    at Object.then (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:79278:39)
    at ZoneDelegate.invoke (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:579:26)
    at Object.onInvoke (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:72557:33)
    at ZoneDelegate.invoke (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:578:52)
    at Zone.run (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:338:43)
    at F:\ionic4-project\learn-project\ionicPWA\dist\server.js:1098:34
    at ZoneDelegate.invokeTask (F:\ionic4-project\learn-project\ionicPWA\dist\server.js:611:31)
    at Object.onInvokeTask (F:\ionic4-project\learn-project\ionicPWA\dist\server\main.js:725

server.ts

/**
 * *** NOTE ON IMPORTING FROM ANGULAR AND NGUNIVERSAL IN THIS FILE ***
 *
 * If your application uses third-party dependencies, you'll need to
 * either use Webpack or the Angular CLI's `bundleDependencies` feature
 * in order to adequately package them for use on the server without a
 * node_modules directory.
 *
 * However, due to the nature of the CLI's `bundleDependencies`, importing
 * Angular in this file will create a different instance of Angular than
 * the version in the compiled application code. This leads to unavoidable
 * conflicts. Therefore, please do not explicitly import from @angular or
 * @nguniversal in this file. You can export any needed resources
 * from your application's main.server.ts file, as seen below with the
 * import for `ngExpressEngine`.
 */

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import * as express from 'express';
import {enableProdMode} from '@angular/core';

import {join} from 'path';

enableProdMode();
const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
  .readFileSync(path.join("dist/browser", "index.html"))
  .toString();
const win = domino.createWindow(templateA);
// win.Object = Object;
// win.Math = Math;
// console.log('win', win);

global["win"] = win;
global["window"] = win;
global["document"] = win.document;
// global["branch"] = null;
// global["object"] = win.object;
// global['HTMLElement'] = win.HTMLElement;
// global['navigator'] = win.navigator;
// global['localStorage'] = win.localStorage;

// global['MutationObserver'] = getMockMutationObserver();

// function getMockMutationObserver() {
//   return class {
//     observe(node, options) {
//     }
//     disconnect() {
//     }
//     takeRecords() {
//       return [];
//     }
//   };
// }

// (global as any).self = {fetch: require('node-fetch')};
// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap} = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 8.1.3
Node: 10.16.3
OS: win32 x64
Angular: 8.1.3
... cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router

Package                                    Version
--------------------------------------------------------------------
@angular-devkit/architect                  0.801.3
@angular-devkit/build-angular              0.801.3
@angular-devkit/build-optimizer            0.801.3
@angular-devkit/build-webpack              0.801.3
@angular-devkit/core                       8.1.3
@angular-devkit/schematics                 8.1.3
@angular/animations                        8.1.2
@ngtools/webpack                           8.1.3
@nguniversal/express-engine                8.1.1
@nguniversal/module-map-ngfactory-loader   8.1.1
@schematics/angular                        8.1.3
@schematics/update                         0.801.3
rxjs                                       6.5.2
typescript                                 3.4.5
webpack                                    4.35.2

ionic info

Ionic:

   Ionic CLI                     : 5.2.7 (C:\Users\yash\AppData\Roaming\nvm\v10.16.3\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.8.0
   @angular-devkit/build-angular : 0.801.3
   @angular-devkit/schematics    : 8.1.3
   @angular/cli                  : 8.1.3
   @ionic/angular-toolkit        : 2.0.0

Utility:

   cordova-res : 0.6.0
   native-run  : 0.3.0

System:

   NodeJS : v10.16.3 (C:\Program Files\nodejs\node.exe)
   npm    : 6.9.0
   OS     : Windows 10

I am stuck in these issues from few days
Please help me to resolve these issues

1 Like

SSR working with ionic please follow this answer