Node.js crashes with a heap out of memory error when V8 runs out of room for JavaScript objects. Learn when to raise the limit and how to find the leak behind it.
The short answer
#V8, the engine inside Node.js, has a size limit for the heap where JavaScript objects live. Your process tried to use more than that and crashed. If the workload is genuinely large, such as a big build, raise the limit with --max-old-space-size. If memory keeps climbing over time, you have a leak to find instead.
_10# allow roughly 4 GB of old-generation heap_10NODE_OPTIONS="--max-old-space-size=4096" npm run build
Why it happens
#V8 splits the heap into a small "young" area for short-lived objects and a larger "old" area for objects that survive garbage collection. The old area has a maximum size. Node.js picks a default based on the memory available to the process, and it is often smaller than the total RAM on your machine.
When the old area fills up, V8 runs increasingly aggressive garbage collections. You may see log lines about "Ineffective mark-compacts near heap limit" just before the crash. If collection cannot free enough space, V8 gives up and Node.js exits with:
_10FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
There are two quite different causes:
- The job really needs more memory. Type checking a large TypeScript project, bundling a big front end, or processing a large file all at once can legitimately go past the default.
- Something is leaking. Objects are kept reachable when they should not be: an ever-growing cache or array, event listeners that are added and never removed, closures holding large data, or timers that are never cleared. Memory rises steadily until the process dies, whatever the limit.
The heap limit only covers JavaScript objects. Buffers and other native memory are counted separately, so a process can also be killed by the operating system or a container limit without this message.
How to fix it
#Raise the heap limit for heavy jobs
--max-old-space-size takes a value in megabytes. Set it through NODE_OPTIONS so it also applies to tools started through npm scripts:
_10{_10 "scripts": {_10 "build": "NODE_OPTIONS=--max-old-space-size=4096 next build"_10 }_10}
On Windows, that inline syntax does not work in cmd. Set the variable in your shell or CI settings instead. Leave headroom for everything else: on a container with 2 GB of memory, a value around 1536 is more sensible than 4096, otherwise the container is killed before V8 ever reports the error.
Stream instead of loading everything
Reading a whole large file or result set into one string or array is a common trigger. Process it in pieces:
_13import { createReadStream } from 'node:fs';_13import { createInterface } from 'node:readline';_13_13const lines = createInterface({_13 input: createReadStream('big-export.csv'),_13 crlfDelay: Infinity,_13});_13_13let count = 0;_13for await (const line of lines) {_13 if (line.includes('error')) count++;_13}_13console.log(count);
The same idea applies to databases: page through results instead of fetching every row at once.
Find the leak with heap snapshots
If memory grows steadily in a long-running server, raising the limit only delays the crash. First confirm the growth by logging memory use:
_10setInterval(() => {_10 const { heapUsed } = process.memoryUsage();_10 console.log(`heapUsed: ${Math.round(heapUsed / 1024 / 1024)} MB`);_10}, 10_000).unref();
Then take heap snapshots and compare them. Start Node.js with the inspector and open chrome://inspect in Chrome, or ask Node.js to write snapshots automatically as it nears the limit:
_10node --inspect server.js_10_10# or write up to 2 snapshots when the heap is close to full_10node --heapsnapshot-near-heap-limit=2 server.js
Load the .heapsnapshot files in the Memory tab of Chrome DevTools and use the comparison view. Look for object types whose count keeps rising between snapshots, then follow the retainers to see what is holding them.
Fix the usual leak patterns
Most leaks come down to a reference that lives longer than it should. A cache with no upper size is a classic:
_11// grows forever_11const cache = new Map();_11_11// bounded: drop the oldest entry once the limit is reached_11const MAX = 1000;_11function remember(key, value) {_11 if (cache.size >= MAX) {_11 cache.delete(cache.keys().next().value);_11 }_11 cache.set(key, value);_11}
Also remove listeners you add per request, clear intervals when work stops, and avoid storing request objects in module-level variables.
Common pitfalls
#- Setting
--max-old-space-sizehigher than the memory the machine or container actually has. The process is then killed by the operating system with no helpful message. - Treating a bigger limit as a fix for a leak. It buys time, but the crash comes back under load.
- Passing the flag to
npmrather than to Node.js. UseNODE_OPTIONSso child processes started by scripts pick it up. - Taking heap snapshots in production without warning. Writing a snapshot pauses the process and can need roughly as much memory again as the heap itself.
- Ignoring native memory. Large
Bufferuse shows up inrssandexternalfromprocess.memoryUsage(), not inheapUsed.
Related reading
#Was this resource helpful?