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

Viewed 7037

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...?

3 Answers

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) {}
}

These globals include window, document, localStorage, indexedDB, setTimeout and setInterval are you can not use in angular universal app

Use document object from Anguar common module

Import from library

import { DOCUMENT } from '@angular/common';

Inject in service

@Inject(DOCUMENT) private document: Document,

Despite its title, it looks like your question is more about slow TTFB than the error with document being undefined.

Regarding that undefined document error, the solution is to:

  • use the following injection @Inject(DOCUMENT) private document if the error appears in your own code

  • use domino if the error appears in 3rd party libraries if you can't replace these libs with other ones that work with angular universal.

To solve the slow TTFB, there is no magic solution. Try to avoid rendering components that do not absolutely need to be rendered server side, make sure you don't have long running API calls, use caching

Related