When encountering the next.js build error below, ensure that all of your environment variables are available at build-time of the container (Docker or other).
Env vars available may be available at run-time only. This happens with docker-compose.yml env_file for example - env vars won't be available until after the container is built and ready, so shelling into the container and running echo $NEXT_PUBLIC_FOO will work, but RUN echo $NEXT_PUBLIC_FOO inside Dockerfile won't work.
💡 To fix it, all env vars must be explicitly listed inside the Dockerfile - this enables docker to leverage layer caching. This way, if an env var changes, docker knows that everything below the corresponding ARG must be rebuilt.
ARG NEXT_PUBLIC_FOO
ARG NEXT_PUBLIC_BAR
ARG NEXT_PUBLIC_BAZ