JavaScript Heap Out of Memory Error
Fix 'JavaScript heap out of memory' errors in Node.js. Learn to increase memory limits, detect memory leaks, and optimize memory usage.
What Does This Error Mean?
The 'JavaScript heap out of memory' error means Node.js has exhausted the memory allocated for the V8 JavaScript engine. This typically happens when processing large datasets, running memory-intensive operations, or due to memory leaks.
Common Causes
Loading an entire large file into memory (e.g., GB-sized JSON)
Memory leak — objects not being garbage collected
Circular references preventing garbage collection
Large arrays or buffers created in a loop without cleanup
Default Node.js memory limit (512MB-1GB) is too low for the workload
Using synchronous file operations that block the event loop
How to Fix It
Increase the Node.js memory limit
Use the --max-old-space-size flag to allocate more memory.
# Increase to 4GB
node --max-old-space-size=4096 app.js
# Set in package.json
"scripts": {
"start": "node --max-old-space-size=4096 app.js"
}Use streams for large files
Process files line by line or in chunks instead of loading everything into memory.
const fs = require("fs")
const readline = require("readline")
// ❌ Loads entire file into memory
const data = JSON.parse(fs.readFileSync("large-file.json", "utf-8"))
// ✅ Process with streams
const rl = readline.createInterface({
input: fs.createReadStream("large-file.json"),
crlfDelay: Infinity
})
rl.on("line", (line) => {
const row = JSON.parse(line)
// Process one row at a time
})Detect memory leaks
Use heap snapshots to find objects that are not being garbage collected.
# Take heap snapshot
node --inspect app.js
# Open chrome://inspect in Chrome
# Monitor memory usage
const used = process.memoryUsage()
console.log(`Heap used: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB`)
console.log(`Heap total: ${(used.heapTotal / 1024 / 1024).toFixed(2)} MB`)Related Tools
Use these tools to debug and fix this error:
Related Errors
Other common errors in this category:
401 Unauthorized Error
Learn what a 401 Unauthorized error means, common causes, and how to fix authentication failures in your web applications.
403 Forbidden Error
Learn what 403 Forbidden means, how it differs from 401, and how to fix access denied errors in your applications.
404 Not Found Error
Learn what 404 Not Found means, common causes, and how to fix broken links and missing resources on your website or API.
429 Too Many Requests Error
Learn what 429 Too Many Requests means, how rate limiting works, and how to handle or avoid hitting API rate limits.