question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ReferenceError: window is not defined

See original GitHub issue

🐞 Bug report

What modules are related to this issue?

  • aspnetcore-engine
  • builders
  • common
  • express-engine
  • hapi-engine
  • module-map-ngfactory-loader

Is this a regression?

No

Description

I was trying to add Angular Universal to our project but, when I use npm run dev:ssr I get the error metioned on the title, here’s the entire message:

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209202:30237)
    at C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209163:37
    at Object../node_modules/jspdf/dist/jspdf.min.js (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:209165:112)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/components/search/search.component.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:255011:15)
    at __
webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/app-routing.module.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:253310:28)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)
    at Object../src/app/app.module.ts (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:253393:30)
    at __webpack_require__ (C:\Users\racp5\Desktop\GRF\Proyecto CMT\cmtFront\CMTProject\dist\cmtFront\server\main.js:20:30)

A server error has occurred.
node exited with 1 code.
connect ECONNREFUSED 127.0.0.1:50593

I tried adding the following code to server.ts, as suggested in another thread of this exact problem, however, this did not work:

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;

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

After this, I really don’t know what to do now, so I come here for help.

Since this is my first time posting here, please tell me if you need something else added.

🔬 Minimal Reproduction

Running npm run server:ssr prompts the error.

🌍 Your Environment


Angular CLI: 9.0.7
Node: 12.16.0
OS: win32 x64

Angular: 9.0.7
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.900.7
@angular-devkit/build-angular     0.900.7
@angular-devkit/build-optimizer   0.900.7
@angular-devkit/build-webpack     0.900.7
@angular-devkit/core              9.0.7
@angular-devkit/schematics        9.0.7
@angular/cdk                      9.2.0
@angular/flex-layout              9.0.0-beta.29
@angular/localize                 9.1.1
@angular/material                 9.2.0
@ngtools/webpack                  9.0.7
@nguniversal/builders             9.1.1
@nguniversal/common               9.0.2
@nguniversal/express-engine       9.0.2
@schematics/angular               9.0.7
@schematics/update                0.900.7
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:2
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

16reactions
jasonburrowscommented, May 12, 2020

To use that workaround it has to appear before import { AppServerModule } from './src/main.server';.

It may not solve your problem though as domino doesn’t implement everything you might need.

1reaction
isawkcommented, Jul 19, 2020

I think I have tried all the implementations on the internet to resolve window not defined issues ssr and third party libraries in this instance keycloak-js and unfortunately nothing seems to work using of domino regardless where I place implementations before import { AppServerModule } from './src/main.server'; after it, an below i have all within export function app(): express.Express and nothing works.

Project needs keycloak and ssr it is an omni channel solution which must implement SSO and enable SEO. Details below.

environment

Angular CLI: 10.0.3
Node: 12.18.2
OS: darwin x64

Angular: 10.0.4
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1000.3
@angular-devkit/build-angular     0.1000.3
@angular-devkit/build-optimizer   0.1000.3
@angular-devkit/build-webpack     0.1000.3
@angular-devkit/core              10.0.2
@angular-devkit/schematics        10.0.3
@angular/cli                      10.0.3
@ngtools/webpack                  10.0.3
@nguniversal/builders             10.0.1
@nguniversal/common               10.0.1
@nguniversal/express-engine       10.0.1
@schematics/angular               10.0.3
@schematics/update                0.1000.3
rxjs                              6.5.5
typescript                        3.9.7
webpack                           4.43.0

//SSR Dom errors polyfile and work around
const domino = require('domino');
import "localstorage-polyfill";

//angular/express
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { existsSync, readFileSync } from 'fs';

const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index.html';

//SSR Dom errors polyfile and work around
const template = readFileSync(join(distFolder, indexHtml)).toString();
const window = domino.createWindow(template);

(global as any).window = window;
(global as any).document = window.document;
(global as any).Event = window.Event;
(global as any).KeyboardEvent = window.KeyboardEvent;
(global as any).MouseEvent = window.MouseEvent;
(global as any).FocusEvent = window.FocusEvent;
(global as any).PointerEvent = window.PointerEvent;
(global as any).HTMLElement = window.HTMLElement;
(global as any).HTMLElement.prototype.getBoundingClientRect = () => {
  return {
    left: '',
    right: '',
    top: '',
    bottom: ''
  };
};
// xmlhttprequest
// (global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
(global as any).navigator = window.navigator;
(global as any).localStorage = window.localStorage;
(global as any).DOMTokenList = window.DOMTokenList;
Object.defineProperty(window.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});
(global as any).CSS = null;
(global as any).Prism = null;
//SSR Dom errors polyfile and work around


import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';


// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {

  const server = express();

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

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

  // 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 || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://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';



error

Compiled successfully. /server/main.js:129404
})(window, function (sha256_imported, base64js_imported) {
   ^

ReferenceError: window is not defined
    at Object../node_modules/keycloak-js/dist/keycloak.js 
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to solve "window is not defined" errors in React and Next.js
First solution: typeof​​ Because typeof won't try to evaluate "window", it will only try to get its type, in our case in Node....
Read more >
How to solve Next.js window is not defined
ReferenceError: window is not defined is a pretty common error you may run into when using Next.js for the first time but don't...
Read more >
referenceerror: window is not defined, how to solve
Here's how to fix the “referenceerror: window is not defined” error that you might have in Node.js or with a tool like Next.js....
Read more >
How To Solve ReferenceError window is not defined in ...
Fixing a window is not defined error can be quite simple. In most cases, all you will need to do is wrap your...
Read more >
[Solved] ReferenceError : window is not defined - ItsJavaScript
The ReferenceError : window is not defined error mainly occurs if you are using the window object in Node.js, React.js, Next.js.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found