react native environment variables

React Native Environment Variables

As a React Native developer, you may need to use environment variables to store sensitive data or configuration values that vary depending on the environment. In this post, we will explore how to use environment variables in React Native.

Creating Environment Variables

In order to use environment variables in your React Native app, you need to create a file called .env at the root of your project. This file should contain your environment variables in the following format:


  VAR_NAME=value

For example, if you want to store the API key for a third-party service, you would create an environment variable like this:


  API_KEY=123456789

Using Environment Variables

After you have created your environment variables in the .env file, you can use them in your React Native app by importing the dotenv module and calling the config() method. This will read the environment variables from the .env file and make them available in your app.


  import dotenv from 'dotenv';
  dotenv.config();
  
  const apiKey = process.env.API_KEY;

You can then use the apiKey variable wherever you need it in your app.

Multiple Environments

If you have different configuration values for different environments (e.g. development, staging, production), you can create separate .env files for each environment (e.g. .env.development, .env.staging, .env.production). You can then use the dotenv module to read the appropriate file depending on the environment:


  import dotenv from 'dotenv';

  switch (process.env.NODE_ENV) {
    case 'development':
      dotenv.config({ path: '.env.development' });
      break;
    case 'staging':
      dotenv.config({ path: '.env.staging' });
      break;
    case 'production':
      dotenv.config({ path: '.env.production' });
      break;
    default:
      throw new Error('NODE_ENV not set correctly.');
  }

  const apiKey = process.env.API_KEY;

By using environment variables in your React Native app, you can keep sensitive data and configuration values separate from your code and easily manage different environments.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe