简体   繁体   English

通过 next.config.js 与使用 NEXT_PUBLIC 前缀在 nextjs 中公开环境变量有什么区别?

[英]What's the difference between exposing environment variables in nextjs through the next.config.js vs with the NEXT_PUBLIC prefix?

According to the nextjs documentation, if I want to expose my environment variables to the browser I can just prefix them with NEXT_PUBLIC in my .env.local file, like so:根据nextjs文档,如果我想向浏览器公开我的环境变量,我可以在我的NEXT_PUBLIC文件中为它们添加前缀.env.local ,如下所示:

NEXT_PUBLIC_VAR=7

However, it looks like I can also expose my environment variables to the browser by using next.config.js , like so:但是,看起来我可以使用next.config.js向浏览器公开我的环境变量,如下所示:

module.exports = {
  env: {
    PUBLIC_VAR: process.env.PUBLIC_VAR,
  },
}

And this will add to the javascript bundle这将添加到 javascript 捆绑包中

What is the difference between these two strategies?这两种策略有什么区别?

The difference between to the two is the one of them uses a.env file whereas the other uses the next.config file.两者的区别在于其中一个使用 a.env 文件,而另一个使用 next.config 文件。 Since Next.js 9.4, loading environment variables with.env files are now supported.从 Next.js 9.4 开始,现在支持使用 .env 文件加载环境变量。

However, to clarify one thing in your question, all environment variables within the.env file don't have to be prefixed with NEXT_PUBLIC , only the ones you want exposed to the browser, any without that prefix will only be accessible on the server.但是,为了澄清您的问题中的一件事, .env 文件中的所有环境变量都不必以NEXT_PUBLIC为前缀,只有您希望向浏览器公开的那些,没有该前缀的任何环境变量都只能在服务器上访问。

NEXT_PUBLIC is a new feature added. NEXT_PUBLIC是添加的新功能。 Before, in order to set up environment variables, we had to set up both for server and client.以前,为了设置环境变量,我们必须同时设置服务器和客户端。

environment variables that are placed in the.env file would be available only on the server-side, if you want to make your env variables available at client-side you had to use next.config.js .放置在 .env 文件中的环境变量只能在服务器端使用,如果你想让你的环境变量在客户端可用,你必须使用next.config.js

With NEXT_PUBLIC , env variables will be available both client-side and server-side.使用NEXT_PUBLIC ,环境变量将在客户端和服务器端都可用。

try this:尝试这个:

place this to.env or env.development file.将此放置到.env 或 env.development 文件。 NOT to next.config.js不要到next.config.js

 MY_VAR=10

then run this:然后运行这个:

    console.log("MY var",process.env.MY_VAR);

both inside client component and getServerSideProps function.在客户端组件和getServerSideProps function 内部。 if you check the browser console, you will get undefined , but on terminal you will see如果你检查浏览器控制台,你会得到undefined ,但在终端上你会看到

MY var 10

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

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