ReferenceError: window is not defined while running serve:ssr

Viewed 332

Whenever I try to build it works fine. But when I try to serve:ssr it throws an error saying window not defined. I read various posts and stacks regarding the same and followed all the instructions still not able to get it working.

I am using angular version 12.0.1

I run these commands simultaneously.

npm run build:ssr
npm run serve:ssr

The build is working fine but serve:ssr gives reference window error.

Reference link followed

I made changes to server.ts file accordingly.

(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

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

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

const distFolder = join(process.cwd(), 'dist/treo/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;

I do not have any window object defined. I converted all of them as described in the reference link.

import { PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from '@angular/common';
import { WindowRef } from './services/windowRef.service';
...
constructor(
 @Inject(PLATFORM_ID) private platformId: any,
 private windowRef: WindowRef
){}
...
if(isPlatformBrowser(this.platformId)) {
  // Use the window reference: this.windowRef
 Eg: this.windowRef.nativeWindow.location.pathname
}

Is there anything more I need to do? Still, I am getting the same error.

ReferenceError: window is not defined

enter image description here

0 Answers
Related