How to correctly set environment variables in Next.js


How to solve Next.js undefined environment variables
To solve Next.js environment variable is undefined Error, you need to make sure it is added on .env.local or on .env.production on server side rendering, and on next.config.js If you using the static generation.
On Server side rendering (SSR) using getServerSideProps
- .env.local to add variables locally, you will notice that it is included in .gitignore file by default if you create your Next.js project using npx create-next-app appName.
- .env.production to add variables on production, this will be pushed to the production and they are available at runtime.
How to add lines to .env file in Next.js
- Define your variable and assign the values like below, you can assign values, json objects
- Restart the environment with CRTL+C and npm run dev
Since environment variables are read once when the server starts, you need to restart the server to take the changes into account, simply press CTRL+C, answer by Y, and then start again the server with npm run dev. Also note that if you change the variable in runtime, this will not take effect until the next restart of the server.
If you would like to read JSON objects from environment variables, use JSON.parse to transform the JSON into a JavaScript object and then manipulate it easily with JavaScript API like Array.prototype.reduce or Array.prototype.map methods, here is my link for more details about JSON and JavaScript objects
On Static Generation with next.config.js
For static page generations using getStaticProps, accessing environment variables with .env.local might not work and give undefined environment issue, to resolve it, declare the variables in the next.config.js file, Here is how to add environment variables to next.config.js.
Add environment variables in NextJs with static generation (getStaticProps)
Add your environment variables in the env object like below, if you have multiple variables add a comma and write your next variable
For example, we have below two variables BASE_URL and nextVar
module.exports = {
reactStrictMode: true,
env: {
BASE_URL: "http://mysite.com",
nextVar: "MyVar",
},
};
In order to take the changes made in next.config.js into effect, you need to restart the server.
Export values
You can also export values or objects using export or export default to expose them to other modules if you do not need some specific informations from process.env.
To learn more about epxorts check my article about it.
Summary
We have seen how to resolve Next.js undefined environment variables by defining the variables in .env files for server side rendering (SSR), and by defining the env file in next.config.js file if you are using static generation.