Immediate Fix: Increasing the Memory Limit
The fastest way to fix the “JavaScript heap out of memory” error is to manually increase the memory limit allocated to the Node.js process. By default, Node.js limits itself to a fraction of the available system memory (often 2GB or 4GB on 64-bit systems).
To fix this immediately, use the --max-old-space-size flag followed by the amount of memory in megabytes (MB) you want to allocate.
# Increase limit to 4GB
node --max-old-space-size=4096 index.js
# Increase limit to 8GB
node --max-old-space-size=8192 script.js
If you are running a script via NPM, you can pass the argument like this:
node --max-old-space-size=4096 $(which npm) run start
Technical Explanation: Why This Happens
Node.js runs on the V8 JavaScript engine. V8 manages memory through a “heap,” where it stores objects and data. When your application processes large datasets or has a memory leak, it exhausts the “Old Space” area of this heap.
When the heap reaches its limit, the Garbage Collector (GC) tries to free up space. If the GC cannot recover enough memory to satisfy an allocation request, Node.js triggers a FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed and crashes to prevent system instability.
| Node.js Version | Default Heap Limit (64-bit) | Recommended Action |
|---|---|---|
| Older versions (< v12) | ~1.5 GB | Manually set –max-old-space-size |
| Modern versions (v14+) | ~2 GB – 4 GB | Check for leaks or increase to 8GB+ |

Alternative Methods and Permanent Fixes
If you don’t want to pass a flag every time you run a command, you can set an environment variable. This is especially useful for build servers (like Jenkins or GitHub Actions) and local development environments.
1. Using NODE_OPTIONS
Setting the NODE_OPTIONS environment variable globally ensures all Node processes respect the new limit.
# For Linux or macOS
export NODE_OPTIONS="--max-old-space-size=4096"
# For Windows (Command Prompt)
set NODE_OPTIONS=--max-old-space-size=4096
# For Windows (PowerShell)
$env:NODE_OPTIONS = "--max-old-space-size=4096"
2. Using Streams for Large Files
If you are processing large files (e.g., CSVs or JSON), don’t use fs.readFile() as it loads the entire file into the heap. Instead, use fs.createReadStream() to process data in chunks.
3. Debugging Memory Leaks
If the error persists even after increasing memory to 8GB or 16GB, your application likely has a memory leak. Use the Node.js built-in inspector to capture heap snapshots and identify objects that are not being garbage collected.
node --inspect index.js