Fixing the JavaScript Heap Out of Memory Error

January, 19th 2025 4 min read

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

bash
node --max-old-space-size=4096 script.js

For Build Tools

bash
node --max-old-space-size=4096 ./node_modules/.bin/webpack

Using Environment Variables

bash
export NODE_OPTIONS="--max-old-space-size=8192"

To confirm the new memory limit:

bash
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:

bash
npm outdated
npm update

If 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:

js
const data = JSON.parse(fs.readFileSync("big.json"));

Use a stream:

js
const stream = fs.createReadStream("big.json");

Clean up unused references

js
bigArray = null;
global.gc && global.gc();

Process work in batches

js
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

js
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

js
setInterval(() => {
  console.log(process.memoryUsage());
}, 2000);

Use heap snapshots

bash
node --inspect script.js

Then 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:

bash
npm cache clean --force

For build systems:

  • Delete .next/, .turbo/, or dist/
  • Remove temporary coverage files
  • Clear CI caches

7. Upgrading Node.js

New Node.js versions improve memory handling.

bash
nvm install stable
nvm use stable

This 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:

json
{
  "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.