Fixing “JavaScript Heap Out of Memory” Error in Node.js

This article will show how you can fix the error “JavaScript Heap Out of Memory” in Node.js.

The “JavaScript heap out of memory” error occurs when the default memory allocated by Node.js is insufficient for a given operation. This guide will walk you through resolving and preventing this error.

Understanding the Error Message

The error message for a “JavaScript Heap Out of Memory” issue usually looks like:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Understanding this message is crucial for effective troubleshooting.

Now, Have a look at the solutions below.

Adjusting Memory Limits

The primary solution involves setting the --max-old-space-size option when running Node.js commands. This option determines the maximum heap size in megabytes. Here’s an example:

node --max-old-space-size=8192 index.js

This sets the memory limit to 8GB. Adjust the value based on your system’s capacity.

Installation of Packages

If the error occurs during package installation, use the following command:

node --max-old-space-size=8192 $(which npm) install express

Replace “express” with the package name you’re installing.

Setting in package.json

To avoid typing the command repeatedly, add it to the scripts section of your package.json file:

{
  "scripts": {
    "prod": "node --max-old-space-size=8192 index.js"
  }
}

Now, use npm run prod to start your server.

Adjusting Memory Size

You can set the --max-old-space-size flag to multiples of 1024. Examples:

# set to 4 GB
node --max-old-space-size=4096 index.js

# set to 6 GB
node --max-old-space-size=6144 index.js

# set to 10 GB
node --max-old-space-size=10177 index.js

Caution on Memory Settings

Avoid setting memory too high, as it might cause system instability or crashes. On a 2GB system, consider setting --max-old-space-size to 1.5GB, leaving room for other processes.

Using Environment Variables

On macOS or Linux:

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

To make it persistent, add this line to your ~/.bashrc, ~/.bash_profile, or ~/.zshrc file.

On Windows:

setx NODE_OPTIONS --max-old-space-size=8192

Setting NODE_OPTIONS Directly in package.json

Install the cross-env package:

npm install --save-dev cross-env

Update your package.json:

{
  "scripts": {
    "prod": "cross-env NODE_OPTIONS='--max-old-space-size=8192' index.js"
  }
}

This ensures cross-platform compatibility for setting environment variables.

By adjusting memory limits and employing these techniques, you can effectively tackle JavaScript heap out of memory errors in your Node.js applications. Choose the method that best fits your workflow and system requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top