6

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.

2
  • @brc-dd it is, check your console, it's logging undefined Commented Jul 9, 2021 at 10:12
  • I need the values in the browser, that was the problem Commented Jul 9, 2021 at 10:19

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Cheers, it's a shame it's like this. Create React App achieves the same level of security (only lets prefixed env variables through) without breaking the object
@bdmason You can try create an object yourself mapping all public environments and use it instead of process.env.
@bcr-dd I saw that was a way to do config, but I wanted it to be gitignored. There did appear to be a way of setting it per environment too, for my project that may be the best solution anyway as client env vars are never secret, and it saves us all passing around env var files. Thanks for the help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.