Fatal error: how to fix Javascript heap out of memory error

Sometimes when a Node.js process runs out of memory while attempting to allocate new objects on the heap you'll into a "FATAL ERROR" message with the details being "Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory".

What is the heap in Node.js and Javascript?

The heap is a region of memory that is used by Node.js in order to store objects created during the execution of a program. When this memory is full, Node.js attempts to allocate more memory, up to a certain limit.

Once that limit is reached and there is still not enough memory available, the process will throw a "FATAL ERROR" message instead.

The error get thrown in a variety of situations, to enumerate a few:

  1. When attempting to process large amounts of data or execute complex algorithms that require a lot of memory.
  2. When running a Node.js server with a large number of connections or concurrent requests.
  3. When running a Node.js application in a container or virtual machine with limited memory resources.

How to fix JavaScript heap out of memory

Linux/MacOS

To fix the error on either Linux or MacOS, you can run the below code to set the maximum heap size to 4GB.

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

Alternatively, if you're using a Docker container to run your Node.js, use this code:

docker run -m 4g myapp

Windows

To fix the same error on Windows installation, follow these steps:

  1. Open Command Prompt or PowerShell as an administrator.
  2. Navigate to your Node.js application directory using the "cd" command.
  3. Run the following command to start your Node.js application with a larger memory limit:
node --max-old-space-size=4096 server.js

Conclusion

Using the above commands you'll be able to fix the JavaScript heap out of memory error on both Linux based operating systems and Windows.

Dealing with bugs is 💩, but not with Jam.

Capture bugs fast, in a format that thousands of developers love.
Get Jam for free