[Angular integration] [ReferenceError: document is not defined]

Author: QHegazyCreated Mar 1, 2024Updated Mar 5, 2024

Describe the bug

When attempting to use server-side rendering (SSR) with Angular and Vite, an error occurs during the evaluation of the server-side rendering module (main.server.mjs). The error is a ReferenceError, stating that document is not defined.

Expected behavior

The application should render without errors during server-side rendering.

Actual behavior

A ReferenceError occurs during the evaluation of the server-side rendering module, specifically related to the document object not being defined.

Show your code

typescript
import {
  Component,
  Inject,
  OnInit,
  PLATFORM_ID,
} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Offcanvas, Ripple, Dropdown, initTWE } from 'tw-elements';
import { isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent implements OnInit {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      if (typeof document !== 'undefined') {
        initTWE({ Offcanvas, Ripple, Dropdown });
      }
    }
  }
}

Desktop

  • OS: [Linux: Fedora@39]
  • Browser [Brave]
  • Version [@Angular:17.2.2]
  • Version [tailwindcss 3.4.1]