Angular 17 SSR, HTTP request server side only

1.8k Views Asked by At

I've been trying out Angular 17's SSR feature. Coming from Next.js, I'm wondering if there's any way to run code only on the server side?

I have tried to use platform ID to figure out where the request is running, and everything seems to be working, but when the application is getting hydrated, it clears out the data that was fetched on the server side.

Can I prevent this behavior somehow?

1

There are 1 best solutions below

0
On

If you want to do fetching server side only, you'll have to transfer that data to the client side if you need to render it.

This is what the TransferState is for (a kind of map to be used as a store).

By using isPlatformServer() you could store the data server side and then restore it on the client side :

class MyService {
  
  platformId = inject(PLATFORM_ID);
  transferState = inject(TransferState);
  myKey = makeStateKey<MyDataInterface>('my-data');
    
  someMethod() {
    if (isPlatformServer(platformId)) {
      transferState.set(myKey, { /* server fetched data */ }); 
    } else {
      transferState.get(myKey); // Do whatever you need
    }
  }
}