Adding type safety to environment variables in NextJS
Feb 5, 2023
Learn how to setup env variable validations in NextJS
I have been working with Next.js for sometime, but we used to find hard time with environment variables mainly when getting started to contribute to existing projects.
Projects usually have
.env.examplefile that helps contributors in setting up the project in local environment where we might be creating
.env.localfile based on the example env. Reason for this is that
.env.localwill be not be tracked in git version control because it might contain sensitive data.
Challenges that one might encounter,
- Unclear Runtime errors because env variables required are not set.
- Unclear compile time errors because env variables required are not set.
- Unexpected behaviour in the application because required variable for local env is not set .... ....
and the list grows...
These challenges are not limited to local, even while deploying to a remote environment like Vercel these env variables when not set will cause run time error but ideally this would have been better if are caught during build time itself.
Validating environment variables is an important step in the development process of any application. Environment variables are used to store sensitive information such as API keys and passwords that should not be stored directly in the codebase. It's essential to validate these variables to ensure that the application is secure and functions correctly.
Here is a step-by-step guide on how to validate environment variables using Zod in a Next.js application:
In your Next.js application, run the following command to install Zod:
Zod allows you to create a schema for your environment variables, which defines the structure and types of variables that you expect. Here's an example of a schema for a few environment variables:
.parsemethod of Zod will parse the object and validates against the
Finally, you have to run the above ones when Next.js builds the application. You can create a file called
env.jsand have the above scripts within it, so that we can easily run them just by importing to
next.config.jsas shown below
Whenever Next.js builds it will consume
next.config.jsconfiguration file and this file be executed at build time and validation happens.
You can also easily consume the env variables with better typing support.
T3 stack template handles this out of the box for you. Please do check that out. You can also handle client and server environment variables separately for fine grain control so that your server secrets doesn't expose to client.
Happy managing environment variables.