In Next.js, is it safe to include API keys in .env.local file and refer to it in getStaticProps?

huangapple go评论67阅读模式
英文:

In Next.js, is it safe to include API keys in .env.local file and refer to it in getStaticProps?

问题

如果我把敏感信息放在文件.env.local中,例如外部API密钥/密钥(并在.gitignore中包含.env.local)。然后,在getStaticProps或getServerSideProps中引用这些敏感信息。

由于getStaticProps或getServerSideProps中的代码在服务器端运行,这是否意味着它无法从浏览器中访问?
或者来自.env.local文件的数据是否会对任何人在浏览器中可用?

英文:

Let's say I put sensitive information in the file .env.local, for example an external API Key/Secret (and include .env.local in .gitignore). Then, I make reference to this sensitive info in getStaticProps or getServerSideProps.

As the code in getStaticProps or getServerSideProps is run server side, does that mean it is not accessible from the browser ?
Or will data from .env.local file be available to anyone from the browser ?

答案1

得分: 2

如果您的应用程序的唯一部分使用环境变量在服务器端运行(getStaticPropsgetServerPropsgetStaticPaths,或者pages/api内的任何内容),浏览器无法访问它们,因此您的密钥是安全的。客户端只能看到它向服务器发出的请求,而不能看到您的服务器向其他API发出的请求。

英文:

If the only part of your app that uses env variables runs server side (getStaticProps, getServerProps, getStaticPaths, or anything inside pages/api) the browser cannot access them, so your keys are safe. The client can only see the request it makes to the server and not the request your server makes to other APIs.

huangapple
  • 本文由 发表于 2023年2月14日 21:22:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定