Reading about garbage collection is one thing; looking inside your actual Next.js Node.js heap is another. Running local production-mode builds with --inspect makes it easy to grab real heap snapshots and catch memory retainers before they hit production.

Capturing heap snapshots via --inspect

Start your Next.js process with --inspect, connect with node inspect --port=<port>, and write snapshots before and after hitting routes:

$ node inspect --port=9230
connecting to 127.0.0.1:9230 ... ok
debug> v8.writeHeapSnapshot('nextjs-before.heapsnapshot')
debug> v8.writeHeapSnapshot('nextjs-after.heapsnapshot')

Load both files into Chrome DevTools -> Memory -> Load, and compare retained sizes across routes.

Dev builds vs. production standalone builds

Early snapshots quickly showed why profiling dev builds misleads:

  • A Next.js dev server held ~67.6 MB, with ~60.8 MB in Strings (mostly in-memory source maps and dev compilation state).
  • The same app running as a production standalone build started at ~29 MB.

Even in production-mode snapshots across repeated route hits, comparing heaps over time turned up three real issues:

  • Hot-path process.env reads: Functions reading process.env.FOO on every render created hundreds of duplicate URI string allocations and stack noise compared to hoisting env reads to module-level constants.
  • Unused response buffers: Carrying raw responseText fields through shared fetch wrappers held onto large strings nobody used.
  • Recursive object-key helpers: Recursive camelize helpers added avoidable stack frames and closure overhead compared to simple iterative versions.

Deleting source maps after upload

Seeing what actually sat in production heaps led directly to setting deleteSourcemapsAfterUpload: true in our error-reporting build step so server containers didn't ship and hold unneeded source maps at runtime.

In production APM graphs right after deploy:

  • Container memory usage: Dropped from ~375 MB to a steady ~250 MB (~33% reduction).
  • Used heap space: Dropped from ~120 MB to ~90 MB (-25%).
  • GC pauses & event loop: Major/minor GC pause durations dropped from 4-6 ms to 2-4 ms, with lower event-loop delay across 4h, 1d, and 1w windows.