英文:
Environment variable doesn't work in getStaticPaths in NextJS
问题
我想在我的 getStaticProps,getStaticPaths 和 API 路由 中,用环境变量替换所有的 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 加载环境变量
奇怪但没问题
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论