TL;DR Getting env vars into a build for Nextjs in AWS CodeBuild can be done using printenv in your prebuild phase in buildspec.yaml

Getting those juicy Environment Variables into your NextJS CodeBuild build

I’ll cut to the chase because I know your time is precious, and I read a hundred rambling blogs to learn what I set out below. Ensure your AWS CodeBuild NextJS build time has access to your environment variables by

  1. Specifying them as Environment Variables for the Build phase of your AWS pipeline (see screenshot)

  2. Adding the line printenv > .env to the pre_build phase in your buildspec.yaml

Build Env Vars on AWS CodeBuild

NextJS Build Time Environment Variables

I’m pretty new to NextJS. Coming up against their confusing implementation of environment variables feels like a rite of passage. Now I know more, I can see why we need to bake in environment variables at build time. Lean and fast are the two critical principles, and dynamically assigning variables at runtime does not conform.

The critical thing to remember is this: Nextjs reads the environment variable values at build time and hardcodes them into the build output. When you run a build, Nextjs will not reference any .env files, even if they are present.

This process isn’t entirely apparent from Nextjs’ otherwise excellent documentation. I suspect this is because if you use Vercel (which is what the creators of NextJS want you to do), getting your environment variables into the build is abstracted away from you.

Running on my machine, I can simply create a local .env file, and we’re golden. I can build it locally and run it successfully in moments. The problems begin when you get fancy and complete your build time workload in the cloud in a pipeline like AWS CodeBuild.  

AWS CodeBuild

You can’t commit your local .env file to your repo because it’s unsafe. You may have passwords, API keys and other secrets in that file, so putting it online is suicidally reckless. Instead, we add our variables as environment variables in the configuration of the AWS CodeBuild build step.

Though AWS CodeBuild allows us to specify environment variables for the build time, unfortunately, NextJS build time doesn’t read these in. Relying simply on AWS environment variables means our build will proceed with our API keys, passwords et al. as undefined, which causes our app serious problems. We need a way to ensure the variables get from the CodeBuild environment into the running container.

As it turns out, you can simply output all environment variables to a file at the root of the Docker container running the CodeBuild build step using this line in the pre_build section of the buildspec.yaml:

printenv > .env

And that’s it. It works. I tore my hair out for a month before I figured this one out—my gift to you.