Fixing the JavaScript Heap Out of Memory Error
The error “FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed – JavaScript heap out of memory” appears when a Node.js process runs out of available memory. Node.js limits the amount of memory a single process can use, and when your application or build tool exceeds this limit, the process crashes.
This guide explains why the error occurs, how to resolve it, and how to prevent it in long‑running or memory‑intensive applications.
Why the Error Happens
Node.js uses the V8 engine, which assigns a default memory limit—typically around 1.5GB to 2GB on 64‑bit systems. Applications that process large datasets, run complex build steps, or generate many objects in memory can hit this limit.
Common causes include:
- Large frontend builds (Webpack, Next.js, Vite)
- Heavy data manipulation scripts
- Unbounded arrays or Maps
- Memory leaks from forgotten timers or references
- Running many parallel tasks in one Node process
Understanding root causes helps decide whether you need more memory or better memory usage.
1. Increasing Node.js Memory Limit
The most direct solution is raising the heap allocation for Node.js. Use the --max-old-space-size flag (value in MB):
Command Line
node --max-old-space-size=4096 script.jsFor Build Tools
node --max-old-space-size=4096 ./node_modules/.bin/webpackUsing Environment Variables
export NODE_OPTIONS="--max-old-space-size=8192"To confirm the new memory limit:
node -e "console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024) + ' MB')"You can set any value your system supports.
2. Updating or Replacing Problematic Dependencies
Memory issues often come from older packages or outdated build tools.
Steps to update:
npm outdated
npm updateIf you’re using tools like Babel, Webpack, TypeScript, or ESLint, upgrades can significantly reduce memory usage due to improved internal optimizations.
3. Optimizing Code for Lower Memory Usage
Sometimes the problem is not the memory limit but how the application uses memory. Consider these improvements:
Avoid loading huge datasets at once
Instead of:
const data = JSON.parse(fs.readFileSync("big.json"));Use a stream:
const stream = fs.createReadStream("big.json");Clean up unused references
bigArray = null;
global.gc && global.gc();Process work in batches
async function chunkProcess(items, size) {
for (let i = 0; i < items.length; i += size) {
const slice = items.slice(i, i + size);
await handle(slice);
}
}This approach avoids holding giant arrays in memory.
Use Worker Threads
import { Worker } from "node:worker_threads";
new Worker("./worker.js", { workerData: bigTask });Workers isolate memory usage per thread.
4. Splitting Build or Processing Tasks
For large build projects:
- Split Webpack builds into client and server bundles.
- Use incremental TypeScript builds.
- Run linters or formatters on changed files only.
For data scripts:
- Write intermediate files rather than keeping everything in RAM.
- Use queues for async tasks.
5. Monitoring and Debugging Memory Usage
To investigate memory leaks or high usage:
Log memory inside your script
setInterval(() => {
console.log(process.memoryUsage());
}, 2000);Use heap snapshots
node --inspect script.jsThen open Chrome DevTools → Memory.
Tools to help
- clinic.js
- heapdump
- Chrome DevTools
- Node.js inspector
These tools identify objects that grow uncontrollably.
6. Clearing Caches
Sometimes cache builds accumulate temporary data:
npm cache clean --forceFor build systems:
- Delete
.next/,.turbo/, ordist/ - Remove temporary coverage files
- Clear CI caches
7. Upgrading Node.js
New Node.js versions improve memory handling.
nvm install stable
nvm use stableThis alone solves memory crashes in many projects.
8. Using Swap Memory (Advanced)
When running on limited hardware (e.g., small VPS), adding swap prevents sudden crashes. This is not as fast as RAM, but helps the system stay alive.
Use only as a last resort.
When Increasing Memory Is Not Enough
If the process still crashes:
- You may have a memory leak.
- Your dataset might be too large for a single process.
- A dependency may be storing too much in memory.
Profiling the app is the next step.
Example: Fixing npm run build
Many developers hit the error during frontend builds. You can patch scripts like this:
{
"scripts": {
"build": "node --max-old-space-size=4096 node_modules/.bin/react-scripts build"
}
}This extends the heap only for the build command.
Final Thoughts
The “JavaScript heap out of memory” error is a practical challenge, especially in large applications and heavy build processes. Increasing memory can temporarily resolve the issue, but long‑term stability comes from updating dependencies, optimizing memory usage, streaming large inputs, or restructuring workloads.
By combining configuration changes with good development practices, you can prevent this error from interrupting your development or production environments.