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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With