Debug and analyze NodeJS Heap

Posted on May 13, 2022

Sometimes you run into issues with memory leaks or JavaScript heap out of memory errors within your NodeJS application and need to analyze it.

The Chrome DevTools ship with a useful tool for this where you can debug your application and inspect the Heap.

The following steps are needed to start inspecting your application:

  1. Start Node process in inspection mode. For this add the --inspect flag in your run command:
node --inspect index.js

For Typescript based projects you can use:

node --inspect -r ts-node/register ./index.ts
  1. Open Debug tools. Type in your Chrome browser:
chrome://inspect
  1. Click on Open dedicated DevTools for Node
  2. Choose the type which you want to see. In the window which opened you can check the CPU Profiler or Memory Profiler - whichever is needed.

Addendum 1: Limiting space size

Wheny our application runs in a Kubernetes cluster or in an environment with limited space, you may want to simulate the memory limits there. For this you can use the --max-old-space-size=512 flag. Which will limit the size of the Heap of the application.

Addendum 2: Differences between –inspect and –inspect-brk

In some documentations you’ll find the flag --inspect-brk instead of --inspect. The difference is that the --inspect-brk code will break before your user code starts.

Further reading