Before nextJS 9.4, we can use next.config.js to set up environment variables, i.e., process.env.* which we can use in our application.
Example of next.config.js like this:
module.exports = {
// other stuffs
env: {
API_HOST:
process.env.NODE_ENV !== "production"
? "http://localhost:3030"
: "http://localhost:5050",
UER_LC_KEY: "DENIUSER-" + process.env.NODE_ENV,
SITE_NAME: "DENIAPPS",
},
};
Then, those environment variables are available in Node.js environment and browser. For example: we can use process.env.API_HOST when we fetch the data in Node.js environment, like
export const getStaticProps = async () => {
const res = await fetch(process.env.API_HOST/posts')
const posts: Post[] = await res.json()
return {
props: {
posts,
},
}
}
Or use process.env.SITE_NAME in a component, like
<Menu.Item header key="menu-0">
<Link href="/">
<a>
<Icon name="world" /> {process.env.SITE_NAME}
</a>
</Link>
</Menu.Item>;
This works fine but has some issues:
Maybe because this, in Next.js versions 9.4 and up, it comes with built-in support for .env* file.
We can now do a lot of things:
NEXT_PUBLIC_SITE_NAME="DENIAPPS"
ready - started server on http://localhost:3000
info - Loaded env from /Projects/next-feathers/next/.env.development.local
info - Loaded env from /Projects/next-feathers/next/.env.local
info - Loaded env from /Projects/next-feathers/next/.env.development
info - Loaded env from /Projects/next-feathers/next/.env
event - compiled successfully
Whatever loading first will be used, so the variable defined in .env.development.local overrides the same variable defined in .env.local, which overrides .env.development, which overrides .env.
"start": "next start -p 8080"
or
npm run start -- --port 8082
There is a small difference between test environment, and both development and production that you need to bear in mind: .env.local won't be loaded, as you expect tests to produce the same results for everyone. This way every test execution will use same env defaults across different executions by ignoring your .env.local (which is intended to override the default set).
Most of environment variables we defined are probably for client side to use, so by using this new feature, all those variables have to be prefixed with NEXT_PUBLIC_., which is a bit ignoring. I would suggest to do the opposite, which is using NEXT_PRIVATE_. prefix for variables ONLY available to Node.js environment.