admin管理员组文章数量:1278795
I cannot access environment variables dynamically in NextJS. In .env.local
I have:
NEXT_PUBLIC_TEST=test
In _app.tsx
I have:
const test = "NEXT_PUBLIC_TEST";
console.log(process.env.NEXT_PUBLIC_TEST); // = 'test'
console.log(process.env[test]); // = undefined
I tried the same thing in Create React APP:
# .env
const test = 'REACT_APP_TEST'
console.log(process.env.REACT_APP_TEST) // = 'test'
console.log(process.env[test]) // = 'test'
Does anybody know why NextJS doesn't allow this and how to override it? I'm aware next.config.js
is a thing, but I'd like to use .env
.
I cannot access environment variables dynamically in NextJS. In .env.local
I have:
NEXT_PUBLIC_TEST=test
In _app.tsx
I have:
const test = "NEXT_PUBLIC_TEST";
console.log(process.env.NEXT_PUBLIC_TEST); // = 'test'
console.log(process.env[test]); // = undefined
I tried the same thing in Create React APP:
# .env
const test = 'REACT_APP_TEST'
console.log(process.env.REACT_APP_TEST) // = 'test'
console.log(process.env[test]) // = 'test'
Does anybody know why NextJS doesn't allow this and how to override it? I'm aware next.config.js
is a thing, but I'd like to use .env
.
- @brc-dd it is, check your console, it's logging undefined – bdmason Commented Jul 9, 2021 at 10:12
- I need the values in the browser, that was the problem – bdmason Commented Jul 9, 2021 at 10:19
1 Answer
Reset to default 11According to the official docs:
Note: In order to keep server-only secrets safe, Next.js replaces
process.env.*
with the correct values at build time. This means thatprocess.env
is not a standard JavaScript object.
Hence what you are trying to do is only possible in development mode, that too in the server side code.
You can manually create an object that maps exposed environment constants and use it instead of process.env
if you truly want to use dynamic values.
Here is an example:
// utils/config.js
export default {
TEST: process.env.NEXT_PUBLIC_TEST
};
// pages/index.js
import config from "../utils/config";
const test = "TEST";
console.log(config[test]);
const IndexPage = () => <div>Hello World</div>;
export default IndexPage;
本文标签: javascriptDynamic access of environment variables in NextJS not workingStack Overflow
版权声明:本文标题:javascript - Dynamic access of environment variables in NextJS not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741258140a2367084.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论