NextJS: Environment Variable Configuration Cheatsheet
Date: 2021-12-30 | nextjs | cloudseed |
Overview
I struggled to get environment variables working with NextJS for the past hour or so - running into tons of environment variable is undefined
errors so wanted to lay out a few pointers that I found helpful and that I think are missing in existing documentation.
Accessing Environment Variables
NextJS has built-in support for environment variables such that you can access some ENVIRONMENT_VARIABLE
via:
process.env.ENVIRONMENT_VARIABLE
Now it should be noted that if you want to use any environment variables in client-side code (like code that is not totally server-side rendered - so probably most of your code that's not dealing with secrets) then you need to prefix your ENVIRONMENT_VARIABLE
with NEXT_PUBLIC_
i.e. NEXT_PUBLIC_ENVIRONMENT_VARIABLE
.
Setting Environment Variables
You make environment variables accessible to NextJS through the use of .env.DEPLOY_ENVIRONMENT
files. For example:
.env.local
-> this will override other defaults.env.development
-> for development.env.production
-> for production
In each of these files, you can set an environment variable like:
MY_ENVIRONMENT_VARIABLE=SOME_VALUE
which can then be accessed in your code like:
process.env.MY_ENVIRONMENT_VARIABLE
Now many times you don't want to have the real value set in a file - like if you want to set secrets as part of your host or maybe you want to set them at the machine level or read them in from your cloud provider etc. You can tell NextJS to fetch the environment variables from the machine by setting the value to $MY_MACHINE_ENV_VARIABLE
So this would be:
MY_VARIABLE=$MY_FETCHED_ENV_VARIABLE
Tips
- Environment variables are set at build time which means that a hot reload will likely not fetch new values. You will probably need to trigger an entire build in order to update values.
- If you are getting undefined values - check if the using code is client or server. Likely it's client and doesn't have access to the variable because you did not use the
NEXT_PUBLIC_
prefix.
Conclusion
NextJS makes a lot of things a lot easier but there's still some pain points involved with making things simple but not providing enough documentation. Hopefully this makes your NextJS configuration journey a bit easier than mine.
I'm building CloudSeed to take care of a lot of these core app configuration woes. It gives you core SaaS app boilerplate with opinionated, sane defaults so you can start coding your app - not wading through documentation.
Together in Software,
-HAMY.OUT
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.