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
import 'localstorage-polyfill'; global['localStorage'] = localStorage;