Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it throws an error.

https://i.stack.imgur.com/w9aeR.png

TypeError: Right-hand side of 'instanceof' is not an object

Initially, I suspected that there might be an error in my code. To test this, I removed all the code and retained only the app component with a simple heading. Surprisingly, it still resulted in the same error.

server.ts

import { enableProdMode } from "@angular/core";
(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');
import 'zone.js/dist/zone-node';
const domino = require('domino');
const fs = require('fs');
const path = require('path');

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { existsSync } from 'fs';
const dotenv = require('dotenv');
dotenv.config();
const distFolder = join(process.cwd(), 'dist/project-name/browser');
const template = fs.readFileSync(path.join(distFolder, 'index.html')).toString();
const win = domino.createWindow(template.toString());
global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
global['getComputedStyle'] = win.getComputedStyle;

// (global as any).self = {fetch: require('node-fetch')};

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/project-name/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

   // Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
   server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

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

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 8000;
  // Start up the Node server
  const server = app();
  server.get('/env', (req, res) => {
    res.json(process.env);
  })
  server.listen(port, () => {
    console.log(`Node Express server listening on https://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';


Could there be something important that I am overlooking?

Answer №1

By utilizing a temporary forked extension for domino, I was able to find a workaround.

  1. To begin, install domino ext by running npm install domino-ext.
  2. In your server.ts file, replace instances of domino with domino-ext.
const domino = require('domino');

Replace it with

const domino = require('domino-ext');

After performing these steps and building your project, everything should work smoothly from thereon.

Source

Answer №2

There seems to be an issue in my setup, as when I tried:

import { createWindow } from 'domino-ext';

An error popped up:

/node_modules/domino-ext/lib/index.d.ts' is not a module.

I managed to fix this by changing the module name from domino to domino-ext:

declare module "domino-ext" {
  function createDOMImplementation(): DOMImplementation;
  function createDocument(html?: string, force?: boolean): Document;
  function createWindow(html?: string, address?: string): Window;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the depths of nested image objects using the map method in ReactJS

I successfully mapped through and destructured this object, but I'm struggling to access the image within the same map. I believe I may need to map through it separately, but I'm uncertain. Here is the object: { "attributes": { ...

The generic parameter is extending a type but is being used in a contravariant position, causing TypeScript to struggle to unify it

When developing my functions, I aim to provide flexibility for consumers to use a wider type. However, I encounter issues when the type is used in a contravariant position and TypeScript raises complaints. Here is the simplified code snippet: function wra ...

What initiates Electron after npm processes the package.json file?

As I delve into the realms of JavaScript, HTML, and Electron, a particular question has been playing on my mind - what exactly happens when you run electron . in the "scripts" -> "start" section of package.json? The mysterious way it operates sends shiv ...

Instructions for automatically sending SMS when there is a change in MySQL database data using PHP

Is it possible to trigger an SMS using Twillo as the gateway when there is a change in data in a MySQL database with PHP? ...

The JSON on the Express page only appears after refreshing the page

When accessing my page at /id, the data pulled from an external API using Express does not display until the page is refreshed. Any suggestions on how to solve this issue? // Retrieves basic account data router.get('/:id', function(req, res, nex ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

Encountering an Unexpected Token in Angular 15, API 29 App

Upon attempting to build and run my Angular application on an Android 10 (API 29) emulator, I encounter a white screen on the device along with the following error message in Android Studio: E/Capacitor/Console: File: http://localhost/ - Line 610 - Msg: Sy ...

Is there a way to set the content to be hidden by default in Jquery?

Can anyone advise on how to modify the provided code snippet, sourced from (http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_show), so that the element remains hidden by default? <!DOCTYPE html> <html> <head> <scrip ...

What is the best method for showcasing this console.log information in an Angular application?

I have developed a feature that displays users who are online. While it works perfectly in the console log, I am struggling to show p as the result if the user is online. Below is the code snippet: ngOnInit() { this.socket.emit('online', { r ...

Encase React black box block components and incorporate DOM event listeners

In my React component, I am using a standard interface to wrap various other components that act as "blackbox" plugins, since I may not have authored them. These plugins must meet certain requirements outlined in the interface to work within the plugin wra ...

Combining the power of Node.js and Node-MySQL with Express 4 and the versatile Mustache

Currently, I am delving into the world of Node.js and encountering a bit of a roadblock. My focus is on passing a query to Mustache. Index.js // Incorporate Express Framework var express = require('express'); // Integrate Mustache Template En ...

Acquire a set of picture cards for displaying in a grid layout

After creating a cardArray to store card objects, I went through each item in the array to generate images as cards. These card images were then appended to the grid div as children. Additionally, I set up an event listener for the shuffle button. However, ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Not all Angular Material2 styles are being fully applied

One issue I am encountering is that styles for components such as <mat-chip> or <button mat-raised-button> (the only ones I have found) are not working properly and appear gray by default. However, styles do apply correctly to the <mat-card& ...

What is the reason behind my styled component only displaying the final state in its className logs?

Here is my implementation using styled components with the version "@types/styled-components": "^5.1.26" and I'll provide you with an example of my code. // index.tsx import React, { useEffect, useState } from 'react'; i ...

What is the best way to determine which variable holds the greatest value in Angular?

I am working with different array lengths stored in variables and trying to determine which variable is the greatest, then change the font color of that variable. However, I encountered an issue where if two variables have the same value, only one is being ...

It only takes half a minute for ts-node-dev to set up its watchers

Having tried both ts-node and ts-node-dev, I am frustrated by the fact that they take almost the same amount of time to start my app server. This issue has been a recurring problem for me, with no successful attempts at resolving it. Currently, I am opera ...

Splitting a row into four columns that will appear consistent on mobile devices

Is it possible to create a row with 4 columns in Angular 6, but have it display as 2 rows with 2 columns each on mobile devices? <div class="row" id="info" *ngIf="this.details"> <div class="col-md-12 mb-3" id="heading"> <h3>Meeting ...

Crop images in a canvas using a customized rectangle with the help of JQuery

I am trying to crop an image inside a Canvas element using a selection rectangle. My project utilizes jQuery and I am in search of a plugin that can help me implement this custom selection rectangle on the canvas itself, not just on images. Are there any ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...