JavaScript remains one of the most-used programming languages due to its versatility. To run JavaScript outside a browser environment, developers must install Node.js, a cross-platform run-time environment. 

The JavaScript heap out of memory error is common when running a JavaScript Node.js project. 

JavaScript heap out of memory problem is an error that occurs when the default memory allocated by the computer system is insufficient to run a big project. 

If you encounter the heap out of memory error, your program will crash and display this output;

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Or 

Fatal error: invalid table size allocation failed - javascript heap out of memory

Causes of JavaScript heap out of memory error

  • Presence of large data structures: Working with large data structures such as matrices or arrays can consume a lot of space, eventually causing heap out of memory error.

This is an example of a large data structure with one billion elements; 

let array = [];

for (let i = 0; i < 1000000000; i  ) {

  array.push(i);

}
  • Poor memory management: As your application grows, you need to let go of some of the objects that you no longer need. 

This is an example of a function that leads to memory leak;

let array = [];

setInterval(function() {

  array.push(new Array(1000000).join("x"));

}, 1000);
  • Infinite loops: Such a code runs forever as a terminating condition is never reached. 

This is an example of an infinite loop that will execute forever;

while (true) {

    console.log(1);

}

Infinite loops can lead to this error as it uses memory pretty fast. 

  • Recursive functions: A recursive function is a function that calls itself indirectly or directly to repeat an/ certain set of instruction(s) until a certain condition(s) is/are met. If these functions are well-designed, they will likely lead to memory lead and, eventually heap of memory error. 
  • Presence of many objects in a piece of code: If your code has many large objects, the memory used up by those objects collectively can lead to an overload. 

Fix JS heap out of memory error

This error can occur in Windows, macOS, and Linux-based operating systems like Ubuntu. Luckily, the error is fixable, irrespective of your operating system. 

#1. Fixing the JavaScript heap out of memory error on Windows OS

Step 1: Click on start menu and locate Advanced System Settings.

Step 2: Click on the Environment Variables on the bottom left part of the dialogue box. 

<img alt="1-3" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/1-3.png" data- decoding="async" height="458" src="data:image/svg xml,” width=”416″>

Step 3: Click New on either User variables or System variables. The first option applies the changes to the current user account. However, the second option applies the changes to the entire system. 

<img alt="2-2" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/2-2.png" data- decoding="async" height="581" src="data:image/svg xml,” width=”622″>

Step 4: There will be two options displayed; on variable name, enter NODE_OPTIONS and on Variable value, enter --max-old-space-size=4096. In this step, the 4096 figure will allocate 4GB virtual memory to Node.js. You can allocate more such as 8GB, by setting the value as –max-old-space-size=8192. 

<img alt="3-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/3-1.png" data- decoding="async" height="156" src="data:image/svg xml,” width=”646″>

Step 5: Click ok, apply and finally, ok to save the changes. 

You can also use the Windows PowerShell terminal to solve the error. Open the terminal on your Windows OS and enter the following command;

env:NODE_OPTIONS="--max-old-space-size=4096"
<img alt="4-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/4-1.png" data- decoding="async" height="505" src="data:image/svg xml,” width=”965″>

You can also solve the error temporarily by running this command before running your app;

set NODE_OPTIONS=--max-old-space-size=4096

#2. Fixing JavaScript heap out of memory error on Linux

  • Step 1: Identify the source of error. Check the console logs or output to determine the lines of code/ file causing the error.
  • Step 2: Export an environment variable specifying the virtual memory you have allocated to Node.js. Use this command; 
export NODE_OPTIONS=--max-old-space-size=4096
<img alt="image-213" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-213.png" data- decoding="async" height="166" src="data:image/svg xml,” width=”1092″>

These steps will allocate 4GB virtual memory to Node.js. If the error still persists, you can increase the memory size by doubling. 

For instance, if you want to allocate 8GB as the virtual memory, you can run this command;

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

#3. Fixing JavaScript heap out of memory error on macOS 

You can solve the JavaScript heap out of memory error in macOS using a similar approach as in Linux. Follow these steps;

  • Step 1: Identify the source of error by checking the console logs or output to determine the lines of code/ file causing the error.
  • Step 2: Export an environment variable specifying virtual memory you have allocated to Node.js. Use this command; 
export NODE_OPTIONS=--max-old-space-size=4096

These steps will allocate 4GB virtual memory to Node.js. If the error still persists, you can increase the memory size by doubling. 

For instance, if you want to allocate 8GB as the virtual memory, you can run this command;

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

Increasing memory during NPM install

The solutions we have offered so far suit errors that occur when you run a Node.js application. However, you can allocate virtual memory to solve heap out of memory error as you install JavaScript packages. Use this command;

node --max-old-space-size=4096 (which npm) install

Note: You can keep increasing virtual memory allocation by 1GB, 2GB, 3GB or 4GB. You must specify memory size in MBs. However, don’t allocate the entire memory of machine to the Node.js as this may cause your program to crash. As a good practise, if your machine has 16GB, you can allocate up to 8GB to Node.js. 

Prevent JavaScript the heap out of memory error

We have so far discussed how to fix the JavaScript heap out-of-memory error when it occurs. Luckily, you can also have measures to prevent this error from occurring as you run JavaScript code. These are some of the best approaches:

#1. Split data into small chunks

You may have a Node.js program that imports large datasets from large CSV files through the ETL: Extract – Transform – Load process. You may find that your app always crashes when you try to import the data. If you are working with MongoDB, you can solve the error by having a command line instruction such as;

split -l 1000000 users.csv

This command instructs Node.js to split a file named users into multiple files with 1000000 users each. The -l flag specifies that the file should be split based on the number of lines of code. 

#2. Monitor memory usage

You can use a memory profiler to detect memory leaks in your code. You can combine Node.js’ inbuilt memory and the ChromeDevTools to achieve this. The two can detect issues in your code and fix them.

You can also use external tools such as Datadog, New Relic and AppDynamics to monitor the performance of your app and take the necessary action. You can also check memory usage on your Node.js app through the process.memoryUsage() method. 

#3. Avoiding memory leaks

Memory leaks occur when your Node.js app retains references to objects that it no longer needs. If such objects are not garbage collected, there will be a build-up of memory usage over time.

There are several approaches to avoid memory leaks, such as avoiding global variables in your code, avoiding blocking I/O operations, and using let and const keywords when declaring your variables instead of var

#4. Spawning processes

If you are running Node.js on a machine with limited memory, such as Raspberry Pi, you are likely to run into heap out of memory errors. You can have one master process, and others are grouped as workers. As soon as the master process detects that the system is running out of memory, it will kill that process and assign the task to another one that is not overloaded. 

#5. Update hardware

If increasing memory allocation and carrying the listed processes of preventing heap out of memory error don’t solve your problems, then you may consider updating your hardware. Node.js can run on RAM as low as 512MB. However, your app will demand more RAM as it grows. 

On the other hand, increasing the number of CPUs can also improve memory allocation. Ideally, 2 or more CPUs will allow your application to use worker threads for CPU-intensive tasks such as cryptography and image processing.

FAQs

What causes JavaScript Heap Out of Memory Error?

This error can be caused by several reasons;

1. Memory leaks

2. Infinite loops

3. Presence of many objects in a project

4. Presence of large data structures

Is JavaScript Heap Out of Memory error solvable?

Yes. You can solve the error through;

1. Allocating more virtual memory to Node.js

2. Eliminating memory leaks

3. Optimizing your code

4. Upgrading your hardware

How can you solve Heap Out of Memory error in React app? 

React is one of the most popular JavaScript libraries. Locate the package.json file on the root directory and these lines to the scripts section;

"scripts": {

    "start": "react-scripts --max_old_space_size=4096 start",

    "build": "react-scripts --max_old_space_size=4096 build",

    "test": "react-scripts test",

    "eject": "react-scripts eject"

}

Wrapping Up

Most developers are used to bugs and code errors, not runtime errors, as they run their Node.js programs. Luckily, you don’t have to worry, as the heap out of memory error is fixable. We have defined what JavaScript heap out of memory error is, explained how to solve it, and how to avoid it in your next Node.js project. 

Next, You may also read how to avoid some common JavaScript Errors.