How to Fix JavaScript Heap Out of Memory Error

A common problem while working on a JavaScript Node.js project is the “JavaScript heap out of memory” error. This error usually occurs when the default memory allocated by your system to Node.js is not enough to run a large project.

The error is common whether you run your project on Windows, macOS, or a Linux distribution like Ubuntu. Luckily, there are a few easy fixes that can help resolve the “JavaScript heap out of memory” error.

What Is Heap Memory?

Before you look at fixing the error, it's useful to understand what heap memory is and how programs use it.

 

Memory allocated on the system heap is also called dynamically allocated memory. It’s up to the programmer to use the available memory as they see fit. More importantly, the heap size for a program depends on the available virtual memory allocated to it.

If you’re running a relatively-large project, it may require more memory than the default allocated chunk. This may cause your project to crash and log the “JavaScript heap out of memory” error.

How to Fix JavaScript Heap Out of Memory on Windows

Regardless of your IDE, the “JavaScript heap out of memory” fix is identical.

You can add an environment variable through Control Panel to increase the memory allocated to a Node.js project.

Open the Start menu, search for Advanced System Settings, and select the Best match. From the dialog box, click on Environment Variables, then click on New from either System variables or User variables. The former applies to all users on your computer, while the latter affects just your current account In the Variable name field enter NODE_OPTIONS. In the Variable value field enter --max-old-space-size=4096. This value will allocate 4GB of virtual memory to Node.js. To set a different value, multiply the amount you require in GB by 1024 (the variable value needs to be in MB).

For more information check this popular resource.