JavaScript heap out of memory solutions tutorial

Posted on Mar 07, 2021

Learn how you can fix JavaScript heap out of memory error

Sometimes, you may saw an error log in your terminal that says JavaScript heap out of memory as seen below:

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

This is commonly caused when JavaScript has a lot of processes to handle, and the default heap memory allocated by Node.js needs more space to process the script you are currently running.

An example of this error can be found when you have too many modules to npm install from your package.json file.

The default Node.js memory limit varies from version to version, but the latest Node.js version 15 still has a memory limit below 2GB.

To fix this kind of error, you need to add the --max-old-space-size option before running your script.

Here’s an example of increasing the memory limit to 4GB:

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

If you want to add the option when running npm install, you can pass the option from Node.js to npm as follows:

node --max-old-space-size=4096 `which npm` install

If you still see the heap out of memory error, then you may need to increase the heap size even more. The memory size starts from 1024 for 1GB:

--max-old-space-size=1024 # increase memory to 1GB
--max-old-space-size=2048 # increase memory to 2GB
--max-old-space-size=3072 # increase memory to 3GB
--max-old-space-size=4096 # increase memory to 4GB

Before the creation of Node.js, JavaScript’s role in web development is limited to manipulating DOM elements in order to create an interactive experience for the users of your web application.

But after the release of Node.js, JavaScript suddenly had a back-end architecture, where you can run complex database queries and other heavy processing before sending data back to the front-end.

JavaScript also saw the rise of npm that allows you to download libraries and modules like React and Lodash.

Many modules downloaded from npm have lots of dependencies on other modules, and some may need to be compiled before they can be used.

The huge amount of tasks JavaScript might handle on the back-end side is why JavaScript may have an out of memory error today.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.