6

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

Techie Sakthi
  • 73
  • 1
  • 8

4 Answers4

14

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) {}
}
Nouli
  • 211
  • 1
  • 3
  • When accessing this document is document could enough or do you need to replace it with this.document since it becomes a local variable? – Martijn Hiemstra Oct 06 '21 at 08:36
  • Use this.document Please see angular.io/guide/dependency-injection-in-action When localStorage is injected, it is used as this.storage.getItem(key) – marcg Mar 10 '22 at 05:26
6

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,
4

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

David
  • 33,444
  • 11
  • 80
  • 118
0

If you have a library that is not compatible with Angular Universal, you should not render this package on the server and you should render it on the client after the response is returned from the server.

isBrowser = false;
constructor(@Inject(PLATFORM_ID) private platformId) {
  this.isBrowser = isPlatformBrowser(this.platformId);
}

now you have to use that package like this:

if (this.isBrowser) {
  ... use package
}

Or you can use ngIf in the html code.