Course contentsShow
← React Native
Lesson 85 of 1,5552. Project Scaffolding with ExpoFree lesson

Environment Variables and Sensitive Data Management

Implement secure configuration handling across development, staging, and production environments.

In this lesson, you will learn how to securely manage configuration settings like API keys across your development, staging, and production environments using Expo.

Why Separate Environments?

When building an app, you often need different settings for different stages of the project. For example, your API_URL might point to a local server while you are coding, a "staging" server for testing, and a live production server for your actual users. Hard-coding these values is dangerous because it leads to errors and risks exposing sensitive secrets, like authentication keys, in your public source code.

Using app.config.js for Environment Handling

In an Expo-managed project, the most secure way to handle these variables is by using a dynamic app.config.js file instead of a static app.json. By exporting a function, you can read environment variables from your operating system and inject them into your app’s configuration at build time.

Implementation Example

First, create a .env file in your project root (and ensure it is added to your .gitignore so it is never pushed to GitHub). Then, set up your app.config.js like this:

import 'dotenv/config';

export default {
  expo: {
    name: "My App",
    extra: {
      apiUrl: process.env.API_URL,
      apiKey: process.env.API_KEY,
    },
  },
};

When you need to use these values inside your React Native components, you access them via the expo-constants package:

import Constants from 'expo-constants';

const apiUrl = Constants.expoConfig.extra.apiUrl;
console.log("Connecting to:", apiUrl);

Security Best Practices

The most important rule in sensitive data management is: never commit secrets to version control. If your API_KEY is in your code, it is public. By using environment variables, you keep the configuration local to your machine or your CI/CD build server. When you run your build, Expo pulls the values from your system's environment, ensuring the secret never touches your repository.

Key Takeaway: Use dynamic configuration files and environment variables to decouple your secrets from your source code, ensuring that sensitive data is injected only at the moment of the build.