How to create an environment variable for Next.js
First, create a file with a starting in .env.
Depending on the run-time environment, a custom .env file can be created suce as the following:
.env.development- when runningnext dev.env.production- when runningnext start.env.local- will override.env,.env.development, and.env.production.env.test- when runningjestORcypress- host environment variables - AWS, Heroku, Vecel, etc. provide an interface to set environment variables directly
Next, inside the created .env file, add the variables to be used
1VARIABLE_NAME=VALUEThis will be accessible via proccess.env
1console.log(process.env.VARIABLE_NAME);Two types of environment variables
- Server-side expose variables
- Browser exposed variables
1. Server-side variables
Every variable set in an .env* file will be available on the server-side. Including the second type
1DB_HOST=secret_host2DB_USERNAME=username3DB_PASSWORD=passwordAbove variables can be used in the server-side code such as getStaticProps, getServerSideProps, or in /api
1export function getStaticProps() {2 connectToDatabase({3 host: process.env.DB_HOST,4 username: process.env.DB_USERNAME,5 password: process.env.DB_PASSWORD,6 })7}2. Browser exposed variables
Accessing the sample variables above will yield undefine.
In order to make a variable available to the browser, it should be prepended with NEXT_PULIC_.
1NEXT_PUBLIC_GOOGLE_ANALYTICS=abcde123452NEXT_PUBLIC_NOT_SO_SECRET_URL=https://example.comEven though there will be more keystrokes, I like this convention as it clearly distinguishes what variables are available to the client-side. It is less likely that I will expose any sensitive information to the user.
As per the variables above, it can be used anywhere in React land. For example, when setting the Google analytics key.
1// _document.tsx2<Head>3 <script4 async5 src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}6 />7</Head>Another usage is for something publicly accessible but should not be committed to the repo.
1useEffect(() => {2 fetch(`${process.env.NEXT_PUBLIC_NOT_SO_SECRET_URL}`)3 // ...4})Although you can still access a browser exposed variable in your server-side code, it will not make sense to do it.
Make sure any sensitive information should not be committed in the repo.
Conclusion
Next.js provides an easy way to set environment variables in any run-time environment. It also provides a good convention to separate variables that can be used on the client-side.
