✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Fix "FATAL ERROR: JavaScript heap out of memory" in Next.js

Published May 21, 2021

I continued running into these OOM (out of memory) errors when using Next.js.

I would encounter an error that looks something like this:

wait - compiling...

<--- Last few GCs --->

[82128:0x102a81000]  5231616 ms: Mark-sweep 2091.9 (2100.2) -> 2091.6 (2100.2) MB, 260.0 / 0.1 ms  (average mu = 0.584, current mu = 0.000) last resort GC in old space requested
[82128:0x102a81000]  5231884 ms: Mark-sweep 2091.6 (2100.2) -> 2090.3 (2100.2) MB, 267.7 / 0.0 ms  (average mu = 0.393, current mu = 0.000) last resort GC in old space requested

<--- JS stacktrace --->

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: 0x100080a4c node::Abort() [/usr/local/Cellar/node/13.13.0_2/bin/node]
2: 0x100080bc2 node::OnFatalError(char const*, char const*) [/usr/local/Cellar/node/13.13.0_2/bin/node]
3: 0x100180be5 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/13.13.0_2/bin/node]
...

And it would continue to display the entire stacktrace.

There seems to be a strict ceiling for memory usage in node (around 1-2 GB on most 64-bit systems).

We can bump that up using the max_old_space_size flag.

--max-old-space-size=<amount of memory in MB>

We would have to run something along the lines of node --max-old-space-size=4096 index.js.

The issue is that Next.js doesn’t allow us to set node properties directly as a flag.

Fortunately, we can just set NODE_OPTIONS before running our next command. Here’s an example with next dev.

// package.json
"scripts": {
    ...
    "dev": "NODE_OPTIONS=--max_old_space_size=4096 next dev",
    ...
},

More JS Articles