How next.config.js sets up environment variables?

Viewed 1138

NexJs is completely new framework for me and I've been studying it.

I'm following this video tutorial and one of the steps is to create a file next.config.js. In this file I put:

module.exports ={
    env: {
        MONGO_URI: "mongodb+srv://username:pwd@cluster0.yxxxx.mongodb.net/ricoapp?retryWrites=true&w=majority"
    }
}

And later I connect to mongo db like this:

console.log('1: ', Object.keys(process.env).includes("MONGO_URI"));
console.log('2: ', "MONGO_URI" in process.env);
console.log('3: ', typeof process.env.MONGO_URI);
console.log('4: ', Object.getOwnPropertySymbols(process.env));
console.log('5: ',process.env.MONGO_URI);
const db = await mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

In the console I get the following output:

1: false

2: false

3: string

4: []

5: mongodb+srv://username:pwd@cluster0.yxxxx.mongodb.net/ricoapp?retryWrites=true&w=majority

So the MONGO_URI is somehow available trough process.env.MONGO_URI but is it seems to me not a property of process.env.

What am I missing here? This doesnt make sense to me.

1 Answers

Environment variables defined in next.config.js are replaced before the server starts. So every occurrence of process.env.MONGO_URI will be replaced with the string value you defined in next.config.js.

Example

Let's say you have a config like this:

// next.config.js
module.exports ={
    env: {
        MY_ENV_VAR: "value_of_my_env_var"
    }
}

And Next.js API function like this:

// pages/api/index.js
export default function handler(req, res) {
  const response = process.env.MY_ENV_VAR;

  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end(response)
}

After running npm run dev or npm run build the code is compiled by webpack to this:

// pages/api/index.js
export default function handler(req, res) {
  const response =  "value_of_my_env_var";

  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end(response)
}

From the docs:

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

Related