Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access system environment variables in Next.js?

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.

like image 239
Aniket Gargya Avatar asked Dec 31 '22 20:12

Aniket Gargya


1 Answers

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.

like image 197
Darryl RN Avatar answered Jan 02 '23 09:01

Darryl RN