To use environment variables when updating a React Native app via CodePush, you can follow these steps:

  1. Set Up Environment Variables: Define your environment-specific variables in separate files, such as .env.staging and .env.production, located in the root of your React Native project. Each file should contain the environment-specific variables. For example:

    // .env.staging API_URL=
    // .env.production API_URL=
  2. Install Dependencies: To manage environment variables in your React Native project, you can use the react-native-dotenv package. Install it using:

    npm install react-native-dotenv --save-dev


    yarn add react-native-dotenv --dev
  3. Configure react-native-dotenv: In the root of your React Native project, create a .env file. This file will contain the default environment variables that will be used when no specific environment is specified. For example:

    // .env API_URL=
  4. Integrate with CodePush: To use environment variables when updating your app via CodePush, you'll need to modify your React Native entry file (index.js or index.tsx) to load the appropriate environment variables from react-native-dotenv and pass them to your app's main component.

    // index.js or index.tsx import { AppRegistry } from 'react-native'; import { name as appName } from './app.json'; import App from './App'; import { loadEnvVars } from 'react-native-dotenv'; // Load the appropriate environment variables based on the CodePush deployment key loadEnvVars(); AppRegistry.registerComponent(appName, () => App);
  5. Deploy the App with CodePush: When deploying your app via CodePush, specify the appropriate deployment key for the target environment. For example, you might use different deployment keys for staging and production deployments.

    For staging:

    code-push release-react MyApp-iOS ios --deploymentName Staging --description "Staging Release" --mandatory

    For production:

    code-push release-react MyApp-iOS ios --deploymentName Production --description "Production Release" --mandatory
  6. Access Environment Variables in Your App: Now, you can access the environment variables anywhere in your app using process.env. For example:

    import { API_URL } from 'react-native-dotenv'; // Use API_URL wherever needed in your app console.log('API URL:', API_URL);

By following these steps, you can set up and use environment variables when updating your React Native app via CodePush, allowing you to configure your app for different environments easily. Remember to use the appropriate deployment key when deploying via CodePush to target the desired environment.

Have questions or queries?
Get in Touch