In this article, we will learn how to solve window is not defined in Angular 11.
window is not defined error occurs when an angular application uses Angular Universal for server-side rendering.
If you want to run your angular application with server-side rendering, you can follow the link given below to implement server-side rendering in Angular.
As Angular – Server-side rendering (SSR) with Angular Universal documentation says:
Because a Universal app doesn’t execute in the browser, some of the browser APIs and capabilities may be missing on the server.
For example, server-side applications can’t reference browser-only global objects such as alert, window, document, navigator, or location.
Let’s follow the steps given below, to solve the window is not defined error.
Firstly execute the command given below to add a mock-browser package.
npm install mock-browser
Now open the server.ts file and add the code to it.
const MockBrowser = require('mock-browser').mocks.MockBrowser; const mock = new MockBrowser(); global['window'] = mock.getWindow();
Rebuild your project with npm run build:ssr and serve with npm run serve:ssr.
Hope all window errors have been suppressed now. Please give your valuable feedback and if you have any questions or issues about this article, please let me know.