Avoiding duplicate HTTP calls in Angular Universal

Cesar Codes
2 min readNov 15, 2018

--

Working with Angular Universal can present a unique set of challenges for developers. Among these is the fact that HTTP calls are duplicated on both the server and client applications.

This issue can be resolved differently depending on your specific scenario.

If your application is making HTTP calls with Angular’s HttpClient, then the solution is rather straightforward. In this case, you can utilize Angular Universal’s TransferHttpCacheModule on your app.module and ServerTransferStateModule on your app.server.module.

Importing the TransferHttpCacheModule into the AppModule.
Importing the ServerTransferStateModule into the AppServerModule.

When you do this. HTTP calls generated with HttpClient will not result in duplicate calls when the Universal app loads on the browser — out of the box.

That’s awesome! BUT… What if you’re not using HttpClient? What if you’re using another HTTP library like Restangular or a GraphQL library, or have a different scenario? In this case, the solution is not so straightforward and TransferHttpCacheModule will not do the trick 😔. However, you can still accomplish the task of eliminating the duplicate call on the browser by utilizing TransferState. The idea here is that when the Universal app executes on the server, you will store the data into a StateKey that you generate using makeStateKey and then when the app executes on the Client, if the data is there (which it will be), the duplicate HTTP call will be bypassed. See the following examples.

First, you still need to bring in ServerTransferStateModule into your app.server.module as shown above. However, on the app.module, you bring in BrowserTransferStateModule so that this can work.

Importing BrowserTransferStateModule into the AppModule

Now that that’s taken care of, it’s time to do the dirty work. Where you call your data, you bring in TransferState and makeStateKey as steps 1 & 3 show below. You then create a StateKey as shown in step 2. Finally, on your actual HTTP call, you will check to see if the StateKey that you created is set, as shown in step 4. When this gets executed for the first time during the server-side rendering, the key will not be set and the code will progress into making the HTTP call as shown in step 6. Now that you have your result, you can set the StateKey as shown in step 7. Now the application gets handed over to the browser and when the same getMyData() function is executed, the StateKey contains the data that you previously set and the subsequent/duplicate HTTP call is avoided.

And that’s it. You have avoided duplicate HTTP calls with Angular Universal. I hope that the NG Universal team continues to do awesome work and that some of this manual work can be relieved from the programmer.

Thanks for reading.

-Cesar

--

--