How do I know if the Angular is running in SSR?

  Kiến thức lập trình

When I was running the Angular application, I tried to use the following code to determine whether the Angular app is running in SSR or CSR.

  const platformId = inject(PLATFORM_ID);
  console.log('Identify CSR: ', isPlatformBrowser(platformId));
  console.log('Identify SSR: ', isPlatformServer(platformId));

When I run it, the “Identify SSR” is true in the console in my VS Code, and the “Identify CSR” is true in the console in my browser.

How can I tell if it is actually running in SSR or not?

If you have "Identify SSR" is true in the console in my VS Code That means the server is running your code before sending to the browser (if no SSR then VS Code won’t log anything) -> so SSR is on.

If you had just "Identify CSR" is true in the console in my browser -> then SSR is not present and you wont get any console messages in VS Code.

The usage of the two functions are as follows:

isPlatformBrowser -> Returns whether a platform id represents a browser platform.


isPlatformServer -> Returns whether a platform id represents a server platform.


An example of usage of these functions is, window and document do not exist on the server, so they will error out when you run the code on the server, by using the isPlatformBrowser, we can ensure the code that uses these objects never run on the server and only on the browser.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT