localStorage undefined Angular Server Side Rendering
Here’s a pretty quick fix to get
localStorage available in your Angular Server-Side Rendering application.
This article assumes you followed the Angular Server-Side Rendering Story: https://github.com/angular/angular-cli/wiki/stories-universal-rendering
npm install localstorage-polyfill
Add this to your
import 'localstorage-polyfill' global['localStorage'] = localStorage;
Rebuild your project.
npm run build:ssr and serve locally as
npm run serve:ssr. All
localStorage errors should be suppressed now.
If you have other errors related to
document undefined and
window undefined, you might wanna try this approach.
mock-browser and use it like this:
const MockBrowser = require('mock-browser').mocks.MockBrowser; const mock = new MockBrowser(); .... global['document'] = mock.getDocument(); global['window'] = mock.getWindow();
You’re good to go!
You don’t have to change ANY part of your actual Angular code. The above approach makes sure
localstorage-polyfillis available for global use.
If you’re wondering how to run your SSR (Server Side Rendering) app in production using Nginx, check out this other article I wrote: Serving Angular SSR via Nginx Proxy