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:
- When attempting to process large amounts of data or execute complex algorithms that require a lot of memory.
- When running a Node.js server with a large number of connections or concurrent requests.
- 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:
- Open Command Prompt or PowerShell as an administrator.
- Navigate to your Node.js application directory using the "cd" command.
- 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.
How Jam can help you debug faster
Running out of heap memory in Node.js can be a challenging problem to debug, especially when you're dealing with complex applications or large data sets. The good news is you can save yourself a lot of time debugging tickets by asking your team to try logging issues with Jam’s free bug reporting browser extension. Jam makes it easy for anyone to create developer-ready bug reports by auto-including console logs, network requests, and steps to reproduce the issue along with the screen recording.
With Jam, you can capture detailed debug data just by recording your screen. Jam packages it all up into a link you can share, or a ticket in your issue tracker. Now everyone can log comprehensive bug reports and developers can fix bugs faster without having to follow up.