← Back to Chapters

React Native Environment Variables

? React Native Environment Variables

? Quick Overview

Environment variables in React Native allow you to store configuration values such as API URLs, keys, and feature flags outside your source code. This helps keep sensitive data secure and makes your app easier to configure for different environments like development, staging, and production.

? Key Concepts

  • Environment variables are key–value pairs.
  • They are resolved at build time, not runtime.
  • Different values can be used for different builds.
  • Commonly stored in .env files.

? Syntax / Theory

React Native does not support environment variables natively like Node.js. External libraries such as react-native-config or Babel plugins are used to inject variables during the build process.

? Code Example(s)

? View Code Example
// .env file storing environment-specific values
API_URL=https://api.example.com
APP_ENV=development
? View Code Example
// Importing environment variables using react-native-config
import Config from "react-native-config";

console.log(Config.API_URL);
console.log(Config.APP_ENV);

? Live Output / Explanation

Expected Output

The console will print the API URL and environment name defined in the .env file. These values change automatically when you switch environment files.

? Interactive Simulator

This tool simulates how react-native-config reads your .env file and makes variables available in JavaScript. Edit the file on the left and click "Simulate Build".

? .env File (Edit Me)

? Generated JS Config

// Click "Simulate Build" to see how to access these variables in JS code...

? Interactive Explanation

Think of environment variables as hidden switches. When you build the app, React Native reads these switches and locks the values into the app bundle. Changing the switch later requires rebuilding the app.

? Use Cases

  • Storing API base URLs
  • Managing feature flags
  • Separating dev and production configurations
  • Hiding sensitive keys from source code

✅ Tips & Best Practices

  • Never commit real secrets to version control.
  • Use different .env files for each environment.
  • Restart the build after changing environment variables.
  • Document required variables for your team.

? Try It Yourself

  1. Create a new .env file.
  2. Add a custom variable like APP_NAME.
  3. Access it inside a React Native component.
  4. Rebuild the app and observe the output.