How To Fix LocalStorage Is Not Defined In Angular

How To Fix LocalStorage Is Not Defined In Angular

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

When an Angular application uses Angular Universal for server-side rendering, the error localStorage 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 localStorage is not defined error, let's follow the steps listed below.

First, we need to install the localstorage-polyfill using the following command.

npm install localstorage-polyfill

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

import 'localstorage-polyfill';
global['localStorage'] = localStorage;

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 "LocalStorage Is Not Defined" is suppressed now and working fine.

Conclusion

In this article, we learned how to Fix "LocalStorage 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