Angular 5 – How to use LocalStorage, Window, Document and other browser types in Angular Universal

Angular 5 - How to use LocalStorage, Window, Document and other browser types in Angular Universal

Developing an Angular Universal (aka isomorphic) application means to write code that can be rendered everywhere, regardless of the client: a web browser, a mobile app, a server-side Node.JS or ASP.NET service that does the prerendering, and so on. This has big advantages in terms of performances, scalability and SEO, but it also comes with some downsides that we need to understand.

The most important of them – and the one causing more issues – is probably the fact that some “global” Javascript objects known as browser types, such as, , and so on are not so “global” anymore: when writing JS code using an universal/isomorphic approach we can’t take them for granted because they simply do not exist on the server, which is one of the contexts we need to take care of.

To better explain this, it means that we can’t do this:

Because it will definitely generate an error during the server-side prerendering phase.

If we need to use these objects, we need to wrap them into a conditional code block that will ensure they’ll be executed only in the appropriate context: in other words, we need to execute these kind of instructions situationally within our JS code, thus adopting anisomorphic approach.

Luckily enough, Angular provides us a way to easily do so by making available two very useful objects:

  • The token (part of the package), which can identify the executing platform’s type.
  • The and methods (from ), which can be used – in conjunction with the aforementioned – to check whether the current platform is browser or server.

Thanks to these two objects we can easily pull off something like this:

These conditional blocks can be put anywhere within our Angular component’s code.

IMPORTANT: Writing isomorphic code and writing decent Angular code are two different things: no matter how conditional and situational our code might be, if we use a global object within an Angular component it means that we’re dealing with this stuff in a bad way. To better understand this concept, I strongly suggest to read this post.

If you want to know more about .NET Core and Angular check out the ASP.NET Core 2 and Angular 5 book, available in paperback and/or digital format!

For more info about Angular Universal and isomorphic JavaScript check out the following resources:

 

RELATED POSTS

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies.

View all posts by Ryan