How to Create Environment Variables Inside next.config.js File and Use them
Written by Kolade Chris | Dec 24, 2022 | #Next.js #WebDev | 1 minute Read
Environment variables let you store secrets you don’t want to expose for security reasons. So, they are useful in concealing private information such as API keys and other secrets.
The normal way many developers create environment variables is to create a .env
file and put the variable identifiers and values there:
But you can also create them inside the next.config.js
file. The benefit is that you won’t need to prefix the variables with NEXT_PUBLIC_
as you can see in the code snippet above.
How to Create env Variables Inside next.config.js
File
Creating environment variables inside the next.config.js
file is not a straightforward process, it is not hard though. What I mean is, you cannot just put them inside the next.config.js
file as you do inside the env
file.
To create environment variables inside the next.config.js
file, you have to define an env
key as a part of the nextConfig
object and put them inside of it in a key:value
pair:
If you are using the latest version of Next JS, the whole file would look like this:
Join my Free Newsletter
Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies.
No BS. No fluff. Just pure software development goodies on a Sunday every week.
How to Use Environment Variables of a next.config.js
File
The reason why you created the environment variables is to use them. So, to use the variables, prefix their names with process.env.
like this:
And if you want to display them in the browser, you can put them inside curly braces:
Thank you for reading. Don’t hesitate to share the article so others who need it can read it.