DEV Community

Krzysztof Platis
Krzysztof Platis

Posted on • Edited on

ngOnDestroy in services - unsubscribe to avoid memory leaks in SSR Angular 💧

I believed that I don’t need to unsubscribe RxJs subscriptions created in Angular singleton services, but only in components. I changed my mind when saw memory leaks in SSR (Angular Universal).

One NodeJS process, but many rendered apps

The NodeJS process of the SSR server on every http request: bootstraps a fresh Angular app, sends the output HTML to the client, and destroys the app. This cycle is repeated for each request inside one shared long-living NodeJS process. So any pending subscription created in any app’s service survives even after the app is destroyed. And it causes memory leaks in the server.

Unsubscribe in services’ ngOnDestroy

Angular invokes in SSR the lifecycle method ngOnDestroy not only for components, but also for every service, when the app is destroyed. Therefore it’s a good place to unsubscribe any pending subscriptions created by the service.

If you really feel like buying me a coffee

... then feel free to do it. Many thanks! 🙌

Buy Me A Coffee

Top comments (1)

Collapse
 
theoklitosbam7 profile image
Theoklitos Bampouris

This is not restricted to SSR. You may check out my article:
dev.to/theoklitosbam7/avoid-memory...