The error ReferenceError: localStorage is not defined
occurs in Angular projects when localStorage
is accessed in an environment where it is not available, such as on the server side during server-side rendering (SSR) using Angular Universal. The localStorage
API is part of the browser's window
object, and it is unavailable in non-browser environments.
To fix this error in your Angular 18 project, you can use the following approaches:
1. Check if localStorage
Exists
Ensure localStorage
is accessed only in the browser. Modify your service or component code to check for its availability before using it.
2. Use Angular's Dependency Injection for Platform Check
Use Angular's PLATFORM_ID
to check whether the code is running in a browser or on the server.
Example:
3. Provide a Fallback for Non-Browser Environments
If the application requires data persistence in both client and server environments, use an alternative to localStorage
, such as an in-memory store.
Example:
4. Handle SSR-Specific Code in the Angular Universal App
If using Angular Universal, make sure localStorage
calls are wrapped and executed only in the browser.
Example in Component:
These approaches will ensure localStorage
is used only in environments where it is available, resolving the error in your Angular 18 project. Let me know if you need further guidance!