Skip to content

How to Fix 'JavaScript heap out of memory' in Node.js

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix 'JavaScript heap out of memory' in Node.js. We cover key concepts, practical examples, and best practices.

The Problem

Your Node.js process crashes with FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - <a href="/programming-languages/javascript/">JavaScript</a> heap out of memory. The V8 JavaScript engine has a default memory limit (typically 512 MB to 2 GB depending on the platform) that your application exceeded. This commonly happens with large data processing, memory leaks, or build tools processing large bundles.

Quick Fix

1. Increase the Node.js memory limit

node --max-old-space-size=4096 app.js

This increases the heap limit to 4 GB. Adjust the number based on your server's available RAM. Each gigabyte is 1024.

2. Set the environment variable

export NODE_OPTIONS="--max-old-space-size=4096"
node app.js

3. Increase memory for build tools

# webpack
NODE_OPTIONS="--max-old-space-size=8192" npx webpack

# Vite
NODE_OPTIONS="--max-old-space-size=4096" npm run build

# Jest
NODE_OPTIONS="--max-old-space-size=4096" npx jest

# TypeScript
NODE_OPTIONS="--max-old-space-size=4096" npx tsc

4. Check current memory usage

node -e "console.log(JSON.stringify(process.memoryUsage(), null, 2))"

Expected output:

{
  "rss": 1245184,
  "heapTotal": 1024000,
  "heapUsed": 548000,
  "external": 15000,
  "arrayBuffers": 10000
}

5. Detect memory leaks with heap snapshots

node --inspect app.js

Open chrome://inspect in Chrome, click "Memory" tab, take a heap snapshot, perform an action, take another snapshot, and compare.

6. Stream data instead of buffering

// Bad: loads entire file into memory
const fs = require('fs');
const data = fs.readFileSync('large-file.csv');
const rows = data.toString().split('\n');

// Good: processes data in streams
const readline = require('readline');
const rl = readline.createInterface({
  input: fs.createReadStream('large-file.csv'),
});
rl.on('line', (line) => {
  // Process one line at a time
});

7. Fix common memory leaks

// Clear intervals
const interval = setInterval(() => {}, 1000);
clearInterval(interval);

// Remove event listeners
emitter.removeAllListeners('data');

// Nullify large references
let largeData = Buffer.alloc(100 * 1024 * 1024);
largeData = null; // Eligible for GC

// Use weak references
const { WeakRef } = require('v8');

Common Causes

Scenario Why OOM Happens Fix
Large build webpack/TypeScript processes thousands of files Increase to 4-8 GB for builds
Memory leak Global variables, closures, event listeners not cleaned up Take heap snapshots with --inspect
Large dataset Reading entire CSV/JSON into memory Stream data instead of buffering
Inadequate default limit Default 512 MB on 32-bit or 2 GB on 64-bit Set --max-old-space-size to 75% of RAM

Check Node.js and npm Versions

node --version
# v18.17.0
npm --version
# 9.6.7

Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.

Prevention

  • Set --max-old-space-size in production process managers (PM2, systemd)
  • Stream large files and API responses instead of buffering them in memory
  • Monitor heap usage with process.memoryUsage() and set up alerts
  • Use --inspect heap snapshots regularly to catch leaks early

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro