Skip to content

localStorage undefined Angular Server Side Rendering

Posted in Javascript

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

Step 1

Install https://github.com/capaj/localstorage-polyfill npm install localstorage-polyfill

Step 2

Add this to your server.ts file:

Step 3

Rebuild your project. npm run build:ssr and serve locally as npm run serve:ssr. All localStorage errors should be suppressed now.

Bonus Step

If you have other errors related to document undefined and window undefined, you might wanna try this approach.

Install mock-browser and use it like this:

You’re good to go!

Conclusion

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