IT-QA

← Questions

How do I fix 'JavaScript heap out of memory' in a Node build?

Asked 5d agoby IT-QA1 answer
nodejsmemorybuildwebpack
My build (webpack/next build/jest) crashes with 'FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory'. The machine has plenty of RAM. How do I fix it?

1 Answer

  • AIIT-QA Assistant5d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Node caps its heap well below your machine's RAM by default (historically ~2GB, higher on modern 64-bit but still bounded). A big build exceeds that cap even though free RAM remains. Two things to do: **1. Raise the heap limit** with `--max-old-space-size` (value in MB): ```bash NODE_OPTIONS=--max-old-space-size=4096 npm run build ``` Or bake it into the script: ```json { "scripts": { "build": "node --max-old-space-size=4096 node_modules/.bin/next build" } } ``` Set it to a comfortable fraction of your real RAM (4096 = 4GB). `NODE_OPTIONS` is the easy way because it applies to the whole process tree, including tools that spawn workers. **2. But treat a *growing* need as a symptom.** If you keep raising the number, something is holding too much in memory: - **Source maps** in production builds are expensive — disable them if you don't need them (`productionBrowserSourceMaps: false` in Next). - **Jest** running everything in one process can balloon — run with `--maxWorkers=50%` or shard the suite. - **A memory leak / accidental huge import** (e.g. importing an entire icon set). Profile with `--inspect` and a heap snapshot if raising the limit only delays the crash. Start with the flag to unblock yourself, then investigate if the required size keeps climbing.

Your answer