环境变量在NextJS的getStaticPaths中不起作用。

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

Environment variable doesn't work in getStaticPaths in NextJS

问题

我想在我的 getStaticPropsgetStaticPathsAPI 路由 中,用环境变量替换所有的 MongoDB 连接 URI 字符串。

从:

const client = await MongoClient.connect(
  'mongodb+srv://XXX:XXX@cluster0.uqztxfp.mongodb.net/meetups?retryWrites=true&w=majority'
)

到:

const client = await MongoClient.connect(`${process.env.MONGODB_URI}`)

.env.local 文件中,MONGODB_URI 的代码如下:

DB_USER='XXX'
DB_PASS='XXX'
MONGODB_URI='mongodb+srv://$DB_USER:$DB_PASS@cluster0.uqztxfp.mongodb.net/meetups?retryWrites=true&w=majority'

它在 getStaticProps 和 api 路由中完美工作,但在 getStaticPaths 中该变量是未定义的…

我阅读的所有文档都说 .env 文件在服务器上通过 getStaticPaths 以及 getStaticProps 和 api 文件夹都是可访问的。

请注意,应用程序在使用硬编码字符串时完美运行。

提前感谢。

英文:

I would like to replace, in my getStaticProps, getStaticPaths and API routes, all mongodb connection URI strings by environment variables

From :

const client = await MongoClient.connect(
  'mongodb+srv://XXX:XXX@cluster0.uqztxfp.mongodb.net/meetups?retryWrites=true&w=majority'
)

To:

const client = await MongoClient.connect(`${process.env.MONGODB_URI}`)

With MONGODB_URI coded like that in .env.local

DB_USER='XXX'
DB_PASS='XXX'
MONGODB_URI='mongodb+srv://$DB_USER:$DB_PASS@cluster0.uqztxfp.mongodb.net/meetups?retryWrites=true&w=majority'

It perfectly works on getStaticProps and api routes, but not with getStaticPaths where variable is undefined...

All documentation I have read says that .env are accessible from server throught getStaticPaths as well as getStaticProps and api folder.

Notice that the app perfectly works with hard coded string

Thanks in advance

答案1

得分: 1

完成。只需删除 .next 文件夹并重新启动我的开发服务器。

我之前没有这样做是因为在每次保存时,我的终端中都会出现下面的消息,而在其他方法中,环境变量是正常的,而且不需要其他操作,只有在 getStaticPaths 中才会出现。

信息  - 从 C:\...\.env.local 加载环境变量

奇怪但没问题 环境变量在NextJS的getStaticPaths中不起作用。

英文:

Done. Just have to delete the .next folder and restart my dev server.

I didn't do it before because I had the message bellow in my terminal on each save and env variables where ok in other methods without any other actions, only in getStaticPaths.

Info  - Loaded env from C:\...\.env.local 

Strange but ok 环境变量在NextJS的getStaticPaths中不起作用。

huangapple
  • 本文由 发表于 2023年3月9日 18:18:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683231.html
匿名

发表评论

匿名网友

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

确定