Next.js javascript heap out of memory

2020-03-13

You might occasionally run into JavaScript heap out of memory errors while building Next.js projects, not to fear! It's typically a simple solution.

To fix the out of memory error you should first look to increase the amount of memory allocated to node.js via the environment variable NODE_OPTIONS.

floppy

Quick Fix?

It's happened to me quite a few times when building a Next.js project with a somewhat large number of pages that I get a Javascript heap out of memory error. This is usually because the node.js process is not allocated enough memory to compile everything. This is especially common in Docker environments because you might not have allocated enough memory compared to your development machine environment. To fix this the first thing to try is to set the NODE_OPTIONS environment variable like NODE_OPTIONS=--max_old_space_size=8192. You can set this anywhere where the next build command will have access to it when running.

Other weird things that might cause the same error

  1. You have some kind of circular dependency or reference (eg component self reference)
  2. If you are using Zeit Now, there is a bug report that this can happen because of a legacy configuration of static assets (not using /public)
  3. There's an open issue on Next.js for other things that might cause the similar error, but my impression it typically is due to a bad or corrupted Next.js setup since it's not easy to create a reproduction that isn't just due to a very large set of pages etc.