Angular

How To Solve LocalStorage Is Not Defined In Angular 11

In this article, we will learn how to solve localStorage is not defined in Angular 11.

localStorage 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.

Server-Side Rendering In Angular 11

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 localStorage is not defined error.

Firstly execute the command given below to implement in-memory localStorage.

npm install localstorage-polyfill

Now open the server.ts file and add the code to it.

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

Rebuild your project with npm run build:ssr and serve with npm run serve:ssr.

Hope all localStorage 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.

Also, check How To Solve Window Is Not Defined In Angular 11

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

View Comments

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago