How to use localStorage on Angular 9 Universal (SSR)

Santi Barbat
2 min readMay 16, 2020
How to use localStorage with Angular 9 Universal (SSR)

In this article I’ll show you how to implement local storage without getting the error:

ERROR ReferenceError: localStorage is not defined

This happens because using Angular Universal for Server Side Rendering, the Angular app runs in both the Nodejs server and the client browser. At this point, the server app does not have a reference to the localStorage object, because it is only available on the client-side. At the Angular Universal documentation we have:

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 window, document, navigator, or location.

How to detect if Angular SSR is executing on the server or on the client browser?

First of all, we need to recognize if our application is running on the browser or in the server:

How to detect server or browser side execution in Angular Universal (SSR)

The localStorage class

We need to make sure we use an abstraction of the localStorage when the app is executed in the server-side, so will use an RxJS Subject to do so:

LocalStorage abstraction service for Angular SSR

And hooray! 🎉, now we can use our service to access the localStorage on the client-side app as described by WEB APIs, without breaking things on the NodeJS server.

Check out what I been up to at: https://comtura.ai

If you like this article, remember to clap 👏. If you feel this article is not good, please leave your feedback in the comments 👇

--

--

Santi Barbat

CTO @ Comtura — London, UK — Argentine, tech & BBQ lover 🍖