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
.
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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With