简体   繁体   English

如何访问Next.js中的系统环境变量?

[英]How to access system environment variables in Next.js?

I created a Next.JS app which uses environment variables.我创建了一个使用环境变量的 Next.JS 应用程序。 I have the environment variables needed as the system's environment variables (because it is a dockerized nextjs app).我有作为系统环境变量所需的环境变量(因为它是一个 dockerized nextjs 应用程序)。

# 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.但仅当在生产模式下运行时, process.env.NEXT_PUBLIC_KEY_NAME在应用程序中未定义。 How can I access them?我怎样才能访问它们? I can't seem to find any documentation on this on Nextjs's website or anywhere else.我似乎无法在 Nextjs 的网站或其他任何地方找到任何关于此的文档。

NextJS Solution NextJS 解决方案

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 . NextJS 内置了支持来完成你想要的,你只需要将你的环境变量放在根文件夹中的.env.local中。

Other than .env.local , you can also use .env , .env.development , and .env.production .除了.env.local ,您还可以使用.env.env.development.env.production

an example of .env.local : .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.瞧,您可以使用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 Docker 解决方案

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.如果上述解决方案不是您正在寻找的解决方案,那么您需要的是如何在 Docker 而不是 NextJS 上设置环境变量。

If you are using docker-compose file:如果您使用的是 docker-compose 文件:

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手册,使用-e参数:

docker run -e NEXT_PUBLIC_KEY_NAME=[insert_what_you_want] frontend bash

or using env file on docker command:或在 docker 命令上使用 env 文件:

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

you can read more from the source .您可以从源代码中阅读更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM