March 5, 2024

How to validate env variables and files using React Native Config

Configuring environment variables correctly is crucial for maintaining the security and functionality of your React Native application. In this step-by-step guide, we'll walk you through validating environment variables in React Native using the react-native-config library. Following these instructions ensures that your app's environment files contain all the necessary variables and files

Let's roll up our sleeves and start coding

Step 1: Install the required dependencies


Step 2: Define your environment variables with Zod

Start by defining your environment variables using the Zod library. Create a file, let’s say env.ts, and add the following code:


Then, we’ll need to create another file called react-native-config.d.ts to have autocompletion and type-safety using Typescript for our variables. Placed this file at your project’s root.


Step 3: Implement the Validation Function

Let’s break down the implementation into three key parts:

First, we need to create a file that contains the validation function, let’s call it validate-env.ts, now we import fs and path node utilities to read the env file. If the file doesn’t exist we throw an error indicating that.


Then, if the file exists we read the content and stored it in a JSON object.


Finally, we use Zod’s safeParse method from the Zod’s object NativeConfig we created before, this will allow us to compare if the jsonObject contains all the variables previously defined without throwing an error, then we check if the parsed.success is false to throw our error parsing errors to see them in the terminal.


You can see the full example of the validate-env.ts file here.

Step 4: Set up the validation process

We are almost there, we need one more dependency to run our validation function. We added ts-node as a dev dependency.


It is time to modify our package.json to update our build scripts to run the validate-env.ts file before building our application.

The goal of adding APP_ENV=environment and ts-node to each build script is to run the validation of the environment file to avoid building an application with missing variables or no variables at all.


APP_ENV will be used in the validate-env.ts file to read the environment variables from the env file. Your implementation could be slightly different from this just, keep in mind that the value of the APP_ENV should be any of the suffixes you used for your files, for example:

.env.production - APP_ENV=production

.env.stg - APP_ENV=stg

Final Thoughts

React Native Config is a great library that enables smooth reading of environment variables in JavaScript and Native code. It also supports TypeScript. By following these simple steps, you can now quickly detect any missing variables or files during the build process and ensure they stay in sync with other variables added by other team members.

Happy coding!