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.

Share Improve this question asked Jul 9, 2021 at 10:00 bdmasonbdmason 5695 silver badges14 bronze badges 2
  • @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
Add a ment  | 

1 Answer 1

Reset to default 11

According 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 that process.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