How To Fix Window Is Not Defined In Angular

How To Fix Window Is Not Defined In Angular

In this article, we will learn how to Fix Window Is Not Defined in an angular application.

When an Angular application uses Angular Universal for server-side rendering, the error window is not declared appears.

if you want to run your Angular application with server-side rendering. You can refer to the server-side rendering in Angular article to implement it.

According to the documentation for Angular - Server-side rendering (SSR) with AngularUniversal:

Some browser APIs and features might not be present on the server since a Universal app doesn't run in the browser.

For instance, global objects like alert, window, document, navigator, and location that are available solely in the browser cannot be referenced by server-side apps.

To resolve the Window is not defined error, let's follow the steps listed below.

First, we need to install the mock-browser using the following command.

npm install mock-browser

Now, add the following code under the server.ts file.

const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();
global['window'] = mock.getWindow();

Now, rebuild your project using the commands npm run build:ssr command and run using the npm run serve:ssr command to serve it.

I hope now your error "Window Is Not Defined" is suppressed now and working fine.

Conclusion

In this article, we learned how to Fix "Window Is Not Defined" in an angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post