Skip to main content

环境变量

Examples

Next.js 内置了对环境变量的支持,它允许你执行以下操作:

¥Next.js comes with built-in support for environment variables, which allows you to do the following:

加载环境变量

¥Loading Environment Variables

Next.js 内置支持将环境变量从 .env.local 加载到 process.env

¥Next.js has built-in support for loading environment variables from .env.local into process.env.

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

注意:Next.js 还支持 .env* 文件内的多行变量:

¥Note: Next.js also supports multiline variables inside of your .env* files:

# .env.local

# you can write with line breaks
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END DSA PRIVATE KEY-----"

# or with `\n` inside double quotes
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END DSA PRIVATE KEY-----\n"

注意:如果你使用的是 /src 文件夹,请注意 Next.js 将仅从父文件夹加载 .env 文件,而不是从 /src 文件夹加载。这会自动将 process.env.DB_HOSTprocess.env.DB_USERprocess.env.DB_PASS 加载到 Node.js 环境中,允许你在 路由处理程序 中使用它们。

¥Note: If you are using a /src folder, please note that Next.js will load the .env files only from the parent folder and not from the /src folder. This loads process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically allowing you to use them in Route Handlers.

例如:

¥For example:

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

使用 @next/env 加载环境变量

¥Loading Environment Variables with @next/env

如果你需要在 Next.js 运行时之外加载环境变量,例如在 ORM 或测试运行程序的根配置文件中,则可以使用 @next/env 包。

¥If you need to load environment variables outside of the Next.js runtime, such as in a root config file for an ORM or test runner, you can use the @next/env package.

Next.js 在内部使用此包从 .env* 文件加载环境变量。

¥This package is used internally by Next.js to load environment variables from .env* files.

要使用它,请安装包并使用 loadEnvConfig 函数加载环境变量:

¥To use it, install the package and use the loadEnvConfig function to load the environment variables:

npm install @next/env
import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)
import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)

然后,你可以在需要的地方导入配置。例如:

¥Then, you can import the configuration where needed. For example:

import './envConfig.ts'

export default defineConfig({
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
})
import './envConfig.js'

export default defineConfig({
dbCredentials: {
connectionString: process.env.DATABASE_URL,
},
})

引用其他变量

¥Referencing Other Variables

Next.js 将自动扩展使用 $ 的变量来引用其他变量,例如 .env* 文件中的 $VARIABLE。这允许你引用其他秘密。例如:

¥Next.js will automatically expand variables that use $ to reference other variables e.g. $VARIABLE inside of your .env* files. This allows you to reference other secrets. For example:

TWITTER_USER=nextjs
TWITTER_URL=https://twitter.com/$TWITTER_USER

在上面的示例中,process.env.TWITTER_URL 将设置为 https://twitter.com/nextjs

¥In the above example, process.env.TWITTER_URL would be set to https://twitter.com/nextjs.

很高兴知道:如果你需要在实际值中使用带有 $ 的变量,则需要对其进行转义,例如 \$

¥Good to know: If you need to use variable with a $ in the actual value, it needs to be escaped e.g. \$.

为浏览器打包环境变量

¥Bundling Environment Variables for the Browser

NEXT_PUBLIC_ 环境变量仅在 Node.js 环境中可用,这意味着浏览器无法访问它们(客户端在不同的环境中运行)。

¥Non-NEXT_PUBLIC_ environment variables are only available in the Node.js environment, meaning they aren't accessible to the browser (the client runs in a different environment).

为了使环境变量的值可以在浏览器中访问,Next.js 可以在构建时将一个值 "inline" 放入交付给客户端的 js 包中,用硬编码值替换对 process.env.[variable] 的所有引用。要告诉它执行此操作,你只需在变量前加上 NEXT_PUBLIC_ 前缀即可。例如:

¥In order to make the value of an environment variable accessible in the browser, Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to process.env.[variable] with a hard-coded value. To tell it to do this, you just have to prefix the variable with NEXT_PUBLIC_. For example:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

这将告诉 Next.js 将 Node.js 环境中对 process.env.NEXT_PUBLIC_ANALYTICS_ID 的所有引用替换为运行 next build 的环境中的值,从而允许你在代码中的任何位置使用它。它将内联到发送到浏览器的任何 JavaScript 中。

¥This will tell Next.js to replace all references to process.env.NEXT_PUBLIC_ANALYTICS_ID in the Node.js environment with the value from the environment in which you run next build, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser.

注意:构建后,你的应用将不再响应这些环境变量的更改。例如,如果你使用 Heroku 管道将一个环境中构建的 slugs 提升到另一个环境,或者如果你构建单个 Docker 映像并将其部署到多个环境,则所有 NEXT_PUBLIC_ 变量将被冻结为构建时评估的值,因此这些 项目构建时需要适当设置值。如果你需要访问运行时环境值,则必须设置自己的 API 以将它们提供给客户端(按需或在初始化期间)。

¥Note: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all NEXT_PUBLIC_ variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to setup your own API to provide them to the client (either on demand or during initialization).

import setupAnalyticsService from '../lib/my-analytics-service'

// 'NEXT_PUBLIC_ANALYTICS_ID' can be used here as it's prefixed by 'NEXT_PUBLIC_'.
// It will be transformed at build time to `setupAnalyticsService('abcdefghijk')`.
setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID)

function HomePage() {
return <h1>Hello World</h1>
}

export default HomePage

请注意,动态查找不会被内联,例如:

¥Note that dynamic lookups will not be inlined, such as:

// This will NOT be inlined, because it uses a variable
const varName = 'NEXT_PUBLIC_ANALYTICS_ID'
setupAnalyticsService(process.env[varName])

// This will NOT be inlined, because it uses a variable
const env = process.env
setupAnalyticsService(env.NEXT_PUBLIC_ANALYTICS_ID)

运行时环境变量

¥Runtime Environment Variables

Next.js 可以支持构建时和运行时环境变量。

¥Next.js can support both build time and runtime environment variables.

默认情况下,环境变量仅在服务器上可用。要将环境变量公开给浏览器,必须以 NEXT_PUBLIC_ 为前缀。但是,这些公共环境变量将在 next build 期间内联到 JavaScript 包中。

¥By default, environment variables are only available on the server. To expose an environment variable to the browser, it must be prefixed with NEXT_PUBLIC_. However, these public environment variables will be inlined into the JavaScript bundle during next build.

要读取运行时环境变量,我们建议使用 getServerSideProps逐步采用 App Router。借助 App Router,我们可以在动态渲染期间安全地读取服务器上的环境变量。这允许你使用单个 Docker 映像,该映像可以通过具有不同值的多个环境进行提升。

¥To read runtime environment variables, we recommend using getServerSideProps or incrementally adopting the App Router. With the App Router, we can safely read environment variables on the server during dynamic rendering. This allows you to use a singular Docker image that can be promoted through multiple environments with different values.

import { unstable_noStore as noStore } from 'next/cache'

export default function Component() {
noStore()
// cookies(), headers(), and other dynamic functions
// will also opt into dynamic rendering, meaning
// this env variable is evaluated at runtime
const value = process.env.MY_VALUE
// ...
}

很高兴知道:

¥Good to know:

默认环境变量

¥Default Environment Variables

一般情况下只需要一个 .env.local 文件。但是,有时你可能想要为 development (next dev) 或 production (next start) 环境添加一些默认值。

¥In general only one .env.local file is needed. However, sometimes you might want to add some defaults for the development (next dev) or production (next start) environment.

Next.js 允许你在 .env(所有环境)、.env.development(开发环境)和 .env.production(生产环境)中设置默认值。

¥Next.js allows you to set defaults in .env (all environments), .env.development (development environment), and .env.production (production environment).

.env.local 始终覆盖默认设置。

¥.env.local always overrides the defaults set.

很高兴知道:.env.env.development.env.production 文件应包含在你的存储库中,因为它们定义了默认值。.env*.local 应添加到 .gitignore,因为这些文件将被忽略。.env.local 是可以存储秘密的地方。

¥Good to know: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored.

Vercel 上的环境变量

¥Environment Variables on Vercel

将 Next.js 应用部署到 Vercel 时,可以配置环境变量 在项目设置中

¥When deploying your Next.js application to Vercel, Environment Variables can be configured in the Project Settings.

所有类型的环境变量都应该在那里配置。甚至开发中使用的环境变量 - 之后可以是 下载到你的本地设备上

¥All types of Environment Variables should be configured there. Even Environment Variables used in Development – which can be downloaded onto your local device afterwards.

如果你已配置 开发环境变量,则可以使用以下命令将它们拉入 .env.local 以在本地计算机上使用:

¥If you've configured Development Environment Variables you can pull them into a .env.local for usage on your local machine using the following command:

vercel env pull .env.local

很高兴知道:将 Next.js 应用部署到 Vercel 时,.env* 文件中的环境变量将不可用于 Edge Runtime,除非它们的名称以 NEXT_PUBLIC_ 为前缀。我们强烈建议你在 项目设置 中管理环境变量,因为所有环境变量都可用。

¥Good to know: When deploying your Next.js application to Vercel, your environment variables in .env* files will not be made available to Edge Runtime, unless their name are prefixed with NEXT_PUBLIC_. We strongly recommend managing your environment variables in Project Settings instead, from where all environment variables are available.

测试环境变量

¥Test Environment Variables

除了 developmentproduction 环境之外,还有第三个选项可用:test。以同样的方式,你可以为开发或生产环境设置默认值,你可以对 testing 环境的 .env.test 文件执行相同的操作(尽管这个文件不像前两个那样常见)。Next.js 不会在 testing 环境中加载 .env.development.env.production 的环境变量。

¥Apart from development and production environments, there is a 3rd option available: test. In the same way you can set defaults for development or production environments, you can do the same with a .env.test file for the testing environment (though this one is not as common as the previous two). Next.js will not load environment variables from .env.development or .env.production in the testing environment.

当使用 jestcypress 等工具运行测试时,你需要仅出于测试目的设置特定的环境变量,这一点很有用。如果 NODE_ENV 设置为 test,则将加载测试默认值,但你通常不需要手动执行此操作,因为测试工具会为你解决该问题。

¥This one is useful when running tests with tools like jest or cypress where you need to set specific environment vars only for testing purposes. Test default values will be loaded if NODE_ENV is set to test, though you usually don't need to do this manually as testing tools will address it for you.

test 环境与 developmentproduction 环境之间存在细微差别,你需要牢记:.env.local 将不会被加载,因为你期望测试为每个人产生相同的结果。这样,每个测试执行都将通过忽略 .env.local (旨在覆盖默认集)在不同的执行中使用相同的环境默认值。

¥There is a small difference between test environment, and both development and production that you need to bear in mind: .env.local won't be loaded, as you expect tests to produce the same results for everyone. This way every test execution will use the same env defaults across different executions by ignoring your .env.local (which is intended to override the default set).

很高兴知道:与默认环境变量类似,.env.test 文件应包含在你的存储库中,但 .env.test.local 不应包含在存储库中,因为 .env*.local 旨在通过 .gitignore 被忽略。

¥Good to know: similar to Default Environment Variables, .env.test file should be included in your repository, but .env.test.local shouldn't, as .env*.local are intended to be ignored through .gitignore.

运行单元测试时,你可以确保以与 Next.js 相同的方式加载环境变量,即利用 @next/env 包中的 loadEnvConfig 函数。

¥While running unit tests you can make sure to load your environment variables the same way Next.js does by leveraging the loadEnvConfig function from the @next/env package.

// The below can be used in a Jest global setup file or similar for your testing set-up
import { loadEnvConfig } from '@next/env'

export default async () => {
const projectDir = process.cwd()
loadEnvConfig(projectDir)
}

环境变量加载顺序

¥Environment Variable Load Order

按顺序在以下位置查找环境变量,一旦找到变量就停止。

¥Environment variables are looked up in the following places, in order, stopping once the variable is found.

  1. process.env

  2. .env.$(NODE_ENV).local

  3. .env.local(当 NODE_ENVtest 时不检查。)

    ¥.env.local (Not checked when NODE_ENV is test.)

  4. .env.$(NODE_ENV)

  5. .env

例如,如果 NODE_ENVdevelopment,并且你在 .env.development.local.env 中都定义了变量,则将使用 .env.development.local 中的值。

¥For example, if NODE_ENV is development and you define a variable in both .env.development.local and .env, the value in .env.development.local will be used.

很高兴知道:NODE_ENV 的允许值为 productiondevelopmenttest

¥Good to know: The allowed values for NODE_ENV are production, development and test.

很高兴知道

¥Good to know

  • 如果你使用的是 /src 目录.env.* 文件应保留在项目的根目录中。

    ¥If you are using a /src directory, .env.* files should remain in the root of your project.

  • 如果未分配环境变量 NODE_ENV,Next.js 在运行 next dev 命令时会自动分配 development,对于所有其他命令会自动分配 production

    ¥If the environment variable NODE_ENV is unassigned, Next.js automatically assigns development when running the next dev command, or production for all other commands.

版本历史

¥Version History

版本变化
v9.4.0支持 .envNEXT_PUBLIC_ 引入。