'Angular Universal/Ionic TypeError: head.querySelector is not a function

While trying to add SSR to an existing Angular/Ionic App, following the Ionic SSR guide, i get the following error TypeError: head.querySelector is not a function After navigating through main.js, i found that >>>

        bootstrapLazy = __name((lazyBundles, options = {}) => {
            const endBootstrap = createTime(),
              cmpTags = [],
              exclude = options.exclude || [],
              customElements2 = win.customElements,
              head = doc.head,
              metaCharset = head.querySelector("meta[charset]"), <<------ Triggers error
              visibilityStyle = doc.createElement("style"),
              deferredConnectedCallbacks = [],
              styles2 = doc.querySelectorAll("[sty-id]");

Angular/Ionic dependencies:

    "@angular/cdk": "^13.3.3",
    "@angular/common": "~13.3.5",
    "@angular/core": "~13.3.5",
    "@angular/forms": "~13.3.5",
    "@angular/localize": "^13.3.5",
    "@angular/material": "^13.3.0",
    "@angular/platform-browser": "~13.3.5",
    "@angular/platform-browser-dynamic": "~13.3.5",
    "@angular/platform-server": "~13.3.5",
    "@angular/router": "~13.3.5",
    "@ionic/angular": "^6.0.0",
    "@ionic/angular-server": "^6.1.4-dev.11651091997.1bc6fa6b",

I have added the required code in server.ts which consists of

const domino = require('domino');
const fs = require('fs');
const path = require('path');

// Use the browser index.html as template for the mock window
const template = fs
  .readFileSync(
    path.join(join(process.cwd(), 'dist/app/browser'), 'index.html')
  )
  .toString();

// Shim for the global window and document objects.
const win = domino.createWindow(template);
global['window'] = win;
global['self'] = win;
global['Node'] = win.Node;
global['Event'] = win.Event;
global['KeyboardEvent'] = win.Event;
global['MouseEvent'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
global['IDBIndex'] = win.IDBIndex;
global['document'] = win.document;
global['doc'] = win.document;
global['navigator'] = win.navigator;

P.S: This is not all the code but the part that was required so the DOM issues don't show.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source