Using Angular TransferState to Fetch and Store A User Variable

Using Angular Transferstate to fetch and store a user variable

In the last tutorial, we created an Angular application and added server-side rendering to it. In this tutorial, we will learn how to fetch the user from our API on the server and transfer it to the browser. A benefit of this is that it creates a global variable where we can access the user without needing to rely on cookies, localStorage, or sessionStorage to persist the user variable between page loads and components. This method will work for any variable as well, such as a dynamic page object, but for this tutorial, we will focus on using Angular’s TranserState to improve our user object fetching speed and security.

Let’s start by opening app.server.module and importing the ServerTransferSteteModule

    imports: [AppModule, ServerModule, ServerTransferStateModule],
    bootstrap: [AppComponent],
export class AppServerModule {}

Then we’ll do the same for app.module, but this time it’s the BrowserTransferStateModule

    declarations: [AppComponent],
    imports: [
        BrowserModule.withServerTransition({ appId: 'serverApp' }),
        // Other imported modules
    bootstrap: [AppComponent],
export class AppModule {}

And after saving, we’ll start up the express server so we can see the transfer happen with npm run dev:ssr

In a component or service of choice, we’ll import our PlatformService we made in the last tutorial. We will also import the TransferState service with private state: TransferState. If it’s a service, all of the following code will go in the constructor, and if it’s a component, we should put the following code in ngOnInit(), but the constructor will work fine.

if (this.platformService.isServer()) {
    let user = USER FETCHED FROM API;
    this.state.set(makeStateKey('user'), user);
} else {
    let user = this.state.get(makeStateKey('user'), null);

OK. First we check if we are in the server. If we are, then we fetch the user from our API, then we store it using the TransferState service. If we’re not in the server, then we get the user from the TransferState service, or set it to null if it doesn’t exist. In the browser, we should be able to see the user object in the developer console without having to fetch it in the browser. Everything is taken care of on the server. Simple as that. Using this method, we can avoid storing the user’s information in localStorage or sessionStorage, preventing leaks from occurring.

The TransferState service’s set function also works in the browser if you need to update the variable.

And remember, this method can be used for any kind of variable, not just for the user. For example, our SEPHIRA content management system uses it to efficiently fetch the dynamic pages, menu entries, and products from the server and transfer it to the browser on first load.

Leave a Reply