7

I created a Next.JS app which uses environment variables. I have the environment variables needed as the system's environment variables (because it is a dockerized nextjs app).

# in terminal
echo $NEXT_PUBLIC_KEY_NAME
# >> value of key

but process.env.NEXT_PUBLIC_KEY_NAME is undefined in the app only when running in production mode. How can I access them? I can't seem to find any documentation on this on Nextjs's website or anywhere else.

1
  • What is the CMD of your Dockerfile? How/What command do you run your app? If you start your Next.js app as a minimal server (next start, node server.js...) you can set env vars before running command and it would not be undefined. If you start your Next.js by building & exporting the static files (next build, next export) and serve them behind a proxy, you have to set env vars before next build Commented Sep 23, 2020 at 7:42

1 Answer 1

12

NextJS Solution

NextJS has built in support to accomplish what you want, you just need to put your environment variables inside .env.local in your root folder.

Other than .env.local, you can also use .env, .env.development, and .env.production.

an example of .env.local:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

in your case, it will become:

NEXT_PUBLIC_KEY_NAME=[insert_what_you_want]

voila, you can access it from your NextJS app, using process.env. keyword.

// pages/index.js
export async function getStaticProps() {
  const db = await myDB.connect({
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
  })
  // ...
}

You can read more from the source.


Docker Solution

If the above solution is not the one you are looking for, then what you need is how to set env variable on Docker instead of NextJS.

If you are using docker-compose file:

frontend:
    image: frontend
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - NEXT_PUBLIC_KEY_NAME=[insert_what_you_want]

if you run the docker manual, use -e parameters:

docker run -e NEXT_PUBLIC_KEY_NAME=[insert_what_you_want] frontend bash

or using env file on docker command:

docker run --env-file ./env.list frontend bash

you can read more from the source.

Sign up to request clarification or add additional context in comments.

3 Comments

do you have an dockerfile for this setup which is working?
I found this solution for docker file: blog.renatopozzi.me/…
@TuanLECONG link is dead, can you share the solution please? Accepted answer doesn't work, runtime docker environment variables are not accessible in next.js browser.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.