angularserver-side-renderingangular-universalangular9

Angular 9 SSR Build Serve eror -- ERROR ReferenceError: document is not defined


ERROR ReferenceError: document is not defined

import { readFileSync } from 'fs';
const domino = require('domino');  // import the library `domino`
const DIST_FOLDER = join(process.cwd(), 'dist/browser');
const template = readFileSync(join(DIST_FOLDER, 'index.html')).toString(); // use `index.html` as template
const win = domino.createWindow(template); // create object Window
global['window'] = win;
global['Event'] = win.Event;               // assign the `win.Event` to prop `Event`
global['document'] = win.document;

Even Adding this in Server.ts Fixing Issue But In Performance TTFB Time is Too High. Any Having the Solution...?


Solution

  • try to use the DOCUMENT constant provided by the @angular/common package

    import { Inject, Injectable } from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    
    @Injectable()
    export class MyService {
      constructor(@Inject(DOCUMENT) private document: Document) {}
    }