Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic access of environment variables in NextJS not working

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.

like image 313
bdmason Avatar asked Mar 01 '23 12:03

bdmason


1 Answers

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;
like image 64
brc-dd Avatar answered Apr 12 '23 14:04

brc-dd