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.
CMDof 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 beforenext build