https://github.com/zeit/next.js/tree/master/examples/with-dotenv
What does the following code on line 1 do in next.config.js? Is it necessary?
require('dotenv').config()
That load environment variables from the .env file to process.env.
It's not required if you are using dotenv-webpack since this load them from .env already but it can help if you want to use those variables inside the next.config.js.
I see. Thanks for the explanation.
Oddly my next app breaks when I leave that line included, and everything works fine when I omit it. I give up trying to figure out why. I can access process.env variables in next.config.js without that line so I'll simply leave it omitted.
require('dotenv').config() requires fs module which is not available on the browser, so it breaks when running require('dotenv').config() on a page/component.
How this ticket can be closed without having proper solution. dotenv is not working in next js. As mentioned by @stoplion , it is throwing error fs module isn't available. I can't imagine how come the example project was created filled with bugs.
You can't require dotenv in components (expectedly as dotenv is a server dependency that does not run in browsers).
Built-in support for .env is coming: https://github.com/zeit/next.js/discussions/11106
Most helpful comment
require('dotenv').config()requiresfsmodule which is not available on the browser, so it breaks when runningrequire('dotenv').config()on a page/component.