How to pass variable from Express.js to Angular11 universal SSR How to pass variable from Express.js to Angular11 universal SSR express express

How to pass variable from Express.js to Angular11 universal SSR


You can provide values from the server and use them in your components/services

server.ts

app.get('*', (req, res) => {      res.render('index', { req, res,  providers: [{ provide: 'message', useValue: 'This is your message' }] })

component.ts

import {Injectable, Inject, PLATFORM_ID, Optional} from '@angular/core';import {isPlatformBrowser} from "@angular/common";import {TransferState, makeStateKey} from '@angular/platform-browser';//Message here is optional because it is only provided in SSR modeconstructor(@Inject(PLATFORM_ID) private platformId: Object,@Optional() @Inject('message') public message: string, private readonly transferState: TransferState){             const storeKey = makeStateKey<string>('messageKey');    if(isPlatformBrowser(this.platformId))//get message from transferState if browser side    {        this.message = this.transferState.get(storeKey, 'defaultMessageValue');    }    else //server side: get provided message and store in in transfer state    {        this.transferState.set(storeKey, this.message);    }            

component.html

<div *ngIf="message">Message from server : {{message}} </div>

With that code, your message will appear in the html rendered by the server (which you can see using view source).

Thanks to transfer state, the message is also available client side

Edit I added instructions so that the message is still available client side