Running a modern frontend build (like Next.js, Vite, or Webpack) on a budget VPS with 1GB or 2GB of RAM often results in a frustrating crash:
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memoryOR
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memoryThe build process simply demands more memory than the V8 engine is willing to use by default, or more than your physical RAM can provide. Here are two ways to solve this.
Method 1: Increase Node's Memory Limit
By default, Node.js might not utilize all the available memory on your system, or it might hit its default limit (often around 512MB or 1.4GB depending on the version and architecture) before utilizing the OS's swap space effectively.
You can force Node.js to allow a larger heap size using the --max-old-space-size flag (in megabytes).
Option A: Export the environment variable
Run this before your build command:
export NODE_OPTIONS="--max-old-space-size=2048"Then run your build:
npm run buildOption B: Run inline
You can also pass it directly in the build command line:
NODE_OPTIONS="--max-old-space-size=2048" npm run buildNote: 2048 MB (2GB) is usually a good starting point. If you have more RAM, you can increase this.
Method 2: Increase Swap Space
If increasing the heap limit isn't enough because your server physically runs out of RAM (causing the OS to kill the process), you need more "virtual" memory. You can add a Swap file to use your disk as temporary RAM.
Here is how to create a 4GB swap file on Linux:
# 1. Allocate a 4GB file
sudo fallocate -l 4G /swapfile
# 2. Set strict permissions (security best practice)
sudo chmod 600 /swapfile
# 3. Mark the file as swap space
sudo mkswap /swapfile
# 4. Enable the swap file
sudo swapon /swapfile
# 5. Verify it's working
sudo swapon --showTo make this permanent (persist after reboot), add it to /etc/fstab:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabConclusion
By combining a larger max-old-space-size with a sufficient Swap file, you can successfully build resource-intensive applications even on the smallest VPS instances.