Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 679
Techie Sakthi Avatar asked Mar 11 '20 12:03

Techie Sakthi


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) {}
}
like image 57
Nouli Avatar answered Oct 19 '22 09:10

Nouli


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,
like image 45
gaurav_thakkar Avatar answered Oct 19 '22 09:10

gaurav_thakkar


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

like image 3
David Avatar answered Oct 19 '22 07:10

David