{"id":26222710,"url":"https://github.com/luggit/react-native-config","last_synced_at":"2026-01-12T06:37:18.173Z","repository":{"id":37580105,"uuid":"52316423","full_name":"lugg/react-native-config","owner":"lugg","description":"Bring some 12 factor love to your mobile apps!","archived":false,"fork":false,"pushed_at":"2024-08-14T11:50:50.000Z","size":3755,"stargazers_count":4839,"open_issues_count":362,"forks_count":659,"subscribers_count":33,"default_branch":"master","last_synced_at":"2024-12-20T09:29:59.655Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lugg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-02-23T00:19:11.000Z","updated_at":"2024-12-12T19:14:01.000Z","dependencies_parsed_at":"2023-12-14T20:57:42.226Z","dependency_job_id":"f4b5cf42-d33d-4a27-ab93-b09cfc051d4d","html_url":"https://github.com/lugg/react-native-config","commit_stats":{"total_commits":277,"total_committers":117,"mean_commits":"2.3675213675213675","dds":0.6498194945848376,"last_synced_commit":"58ea23a27a7ba6a8d7db7171188bd245265be23a"},"previous_names":["luggg/react-native-config","luggit/react-native-config"],"tags_count":63,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lugg%2Freact-native-config","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lugg%2Freact-native-config/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lugg%2Freact-native-config/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lugg%2Freact-native-config/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lugg","download_url":"https://codeload.github.com/lugg/react-native-config/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243258487,"owners_count":20262298,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-12T17:01:53.987Z","updated_at":"2025-03-12T17:01:59.439Z","avatar_url":"https://github.com/lugg.png","language":"Java","readme":"# Config variables for React Native apps\n\nModule to expose config variables to your javascript code in React Native, supporting iOS, Android, macOS and Windows.\n\nBring some [12 factor](http://12factor.net/config) love to your mobile apps!\n\n## Basic Usage\n\nCreate a new file `.env` in the root of your React Native app:\n\n```\nAPI_URL=https://myapi.com\nGOOGLE_MAPS_API_KEY=abcdefgh\n```\n\nThen access variables defined there from your app:\n\n```js\nimport Config from \"react-native-config\";\n\nConfig.API_URL; // 'https://myapi.com'\nConfig.GOOGLE_MAPS_API_KEY; // 'abcdefgh'\n```\n\nKeep in mind this module doesn't obfuscate or encrypt secrets for packaging, so **do not store sensitive keys in `.env`**. It's [basically impossible to prevent users from reverse engineering mobile app secrets](https://rammic.github.io/2015/07/28/hiding-secrets-in-android-apps/), so design your app (and APIs) with that in mind.\n\n## Setup\n\nInstall the package:\n\n```\n$ yarn add react-native-config\n```\n\nLink the library:\n\n(Note: For React Native 0.60 or greater, [autolinking](https://reactnative.dev/blog/2019/07/03/version-60#native-modules-are-now-autolinked) is available)\n\n(Note: For Windows, this module supports autolinking when used with `react-native-windows@0.63`\nor later. For earlier versions you need to manually link the module.)\n\n```\n$ react-native link react-native-config\n```\n\nif cocoapods are used in the project then pod has to be installed as well:\n\n```\n(cd ios; pod install)\n```\n\n - Manual Link (iOS / macOS)\n\n\t1. In XCode, in the project navigator, right click `Libraries` ➜ `Add \t\tFiles to [your project's name]`\n\t2. Go to `node_modules` ➜ `react-native-config` ➜ `ios`  and add \t\t`ReactNativeConfig.xcodeproj`\n\t3. Expand the `ReactNativeConfig.xcodeproj` ➜ `Products` folder\n\t4. In the project navigator, select your project. Add \t\t`libRNCConfig.a` to your project's `Build Phases` ➜ `Link Binary With Libraries`\n\t5. And go the Build Settings tab. Make sure All is toggled on (instead of Basic)\n\t6. Look for Header Search Paths and add `$(SRCROOT)/../node_modules/react-native-config/ios/**` as `non-recursive`\n\n\n - Manual Link (Android) \n\n\t**android/settings.gradle**\n\t\n\t```diff\n\t+ include ':react-native-config'\n\t+ project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')\n\t```\n\t**android/app/build.gradle**\n\t\n\t```diff\n\tdependencies {\n\t\timplementation \"com.facebook.react:react-native:+\"  // From node_modules\n\t+\timplementation project(':react-native-config')\n\t}\n\t```\n\t**MainApplication.java**\n\t\n\t```diff\n\t+ import com.lugg.RNCConfig.RNCConfigPackage;\n\t\n\t@Override\n\tprotected List\u003cReactPackage\u003e getPackages() {\n\t\t   return Arrays.asList(\n           \t\tnew MainReactPackage()\n\t+      \t\tnew RNCConfigPackage()\n\t    );\n\t}\n\t```\n\n - Manual Link (Windows)\n\n\t**windows/myapp.sln**\n\n\tAdd the `RNCConfig` project to your solution.\n\n\t1. Open the solution in Visual Studio 2019\n\t2. Right-click Solution icon in Solution Explorer \u003e Add \u003e Existing Project  \n\t  - if using `react-native-windows@0.62` or later select `node_modules\\react-native-config\\windows\\RNCConfig\\RNCConfig.vcxproj`\n\t\t- if using `react-native-windows@0.61` select `node_modules\\react-native-config\\windows\\RNCConfig61\\RNCConfig61.vcxproj`\n\n\t**windows/myapp/myapp.vcxproj**\n\n\tAdd a reference to `RNCConfig` to your main application project. From Visual Studio 2019:\n\n\t1. Right-click main application project \u003e Add \u003e Reference...  \n\tCheck `RNCConfig` from Solution Projects.\n\n\t**pch.h**\n\n\tAdd `#include \"winrt/RNCConfig.h\"`.\n\n\t**app.cpp**\n\n\tAdd `PackageProviders().Append(winrt::RNCConfig::ReactPackageProvider());` before `InitializeComponent();`.\n\n### Extra step for Android\n#### Using RN-Integrate\nApply extra steps automatically:\n```sh\nnpx react-native-integrate react-native-config\n```\n\n#### Manual\nYou'll also need to manually apply a plugin to your app, from `android/app/build.gradle`:\n\n```\n// 2nd line, add a new apply:\napply from: project(':react-native-config').projectDir.getPath() + \"/dotenv.gradle\"\n```\n\n#### Advanced Android Setup\n\nIn `android/app/build.gradle`, if you use `applicationIdSuffix` or `applicationId` that is different from the package name indicated in `AndroidManifest.xml` in `\u003cmanifest package=\"...\"\u003e` tag, for example, to support different build variants:\nAdd this in `android/app/build.gradle`\n\n```\ndefaultConfig {\n    ...\n    resValue \"string\", \"build_config_package\", \"YOUR_PACKAGE_NAME_IN_ANDROIDMANIFEST_XML\"\n}\n```\n\n## TypeScript declaration for your .env file\n\nIf you want to get autocompletion and typesafety for your .env files. Create a file named `react-native-config.d.ts` in the same directory where you put your type declarations, and add the following contents:\n\n```ts\ndeclare module 'react-native-config' {\n  export interface NativeConfig {\n      HOSTNAME?: string;\n  }\n  \n  export const Config: NativeConfig\n  export default Config\n}\n```\n\nThen when you want to use it, you just write:\n\n```\nimport Config from 'react-native-config';\nconsole.log(Config.HOSTNAME);\n```\n\n## Native Usage\n\n### Android\n\nConfig variables set in `.env` are available to your Java classes via `BuildConfig`:\n\n```java\npublic HttpURLConnection getApiClient() {\n    URL url = new URL(BuildConfig.API_URL);\n    // ...\n}\n```\n\nYou can also read them from your Gradle configuration:\n\n```groovy\ndefaultConfig {\n    applicationId project.env.get(\"APP_ID\")\n}\n```\n\nAnd use them to configure libraries in `AndroidManifest.xml` and others:\n\n```xml\n\u003cmeta-data\n  android:name=\"com.google.android.geo.API_KEY\"\n  android:value=\"@string/GOOGLE_MAPS_API_KEY\" /\u003e\n```\n\nAll variables are strings, so you may need to cast them. For instance, in Gradle:\n\n```\nversionCode project.env.get(\"VERSION_CODE\").toInteger()\n```\n\nOnce again, remember variables stored in `.env` are published with your code, so **DO NOT put anything sensitive there like your app `signingConfigs`.**\n\n### iOS / macOS\n\nRead variables declared in `.env` from your Obj-C classes like:\n\n```objective-c\n// import header\n#import \"RNCConfig.h\"\n\n// then read individual keys like:\nNSString *apiUrl = [RNCConfig envFor:@\"API_URL\"];\n\n// or just fetch the whole config\nNSDictionary *config = [RNCConfig env];\n```\n\n### Windows\n\nYou can access variables declared in `.env` from C++ in your App project:\n```\nstd::string api_key = ReactNativeConfig::API_KEY;\n```\n\nSimilarly, you can access those values in other project by adding reference to the `RNCConfig` as described in the manual linking section.\n\n### Availability in Build settings and Info.plist\n\nWith one extra step environment values can be exposed to \"Info.plist\" and Build settings in the native project.\n\n1. click on the file tree and create new file of type XCConfig\n   ![img](./readme-pics/1.ios_new_file.png)\n   ![img](./readme-pics/2.ios_file_type.png)\n2. save it under `ios` folder as \"Config.xcconfig\" with the following content:\n\n```\n#include? \"tmp.xcconfig\"\n```\n\n3. add the following to your \".gitignore\":\n\n```\n# react-native-config codegen\nios/tmp.xcconfig\n\n```\n\n4. go to project settings\n5. apply config to your configurations\n   ![img](./readme-pics/3.ios_apply_config.png)\n6. Go to _Edit scheme..._ -\u003e _Build_ -\u003e _Pre-actions_, click _+_ and select _New Run Script Action_. Paste below code which will generate \"tmp.xcconfig\" before each build exposing values to Build Settings and Info.plist. Make sure to select your target under _Provide build settings from_, so `$SRCROOT` environment variables is available to the script. (Note that this snippet has to be placed after \"cp ... \\${PROJECT_DIR}/../.env\" if [approach explained below](#ios-multi-scheme) is used).\n\n   ```\n   \"${SRCROOT}/../node_modules/react-native-config/ios/ReactNativeConfig/BuildXCConfig.rb\" \"${SRCROOT}/..\" \"${SRCROOT}/tmp.xcconfig\"\n   ```\n\n   ![img](./readme-pics/4.ios_pre_actions.png)\n\n7. You can now access your env variables in the Info.plist, for example `$(MY_ENV_VARIABLE)`. If you face issues accessing variables, please open a new issue and provide as much details as possible so above steps can be improved.\n\n#### App Extensions\n\nAdd dependency to `react-native-config`.\n\n```\ntarget 'ShareExtension' do\n  platform :ios, '9.0'\n\n  pod 'react-native-config', :path =\u003e '../node_modules/react-native-config'\n\n  # For extensions without React dependencies\n  pod 'react-native-config/Extension', :path =\u003e '../node_modules/react-native-config'\nend\n```\n\n### Different environments\n\nSave config for different environments in different files: `.env.staging`, `.env.production`, etc.\n\nBy default react-native-config will read from `.env`, but you can change it when building or releasing your app.\n\nThe simplest approach is to tell it what file to read with an environment variable, like:\n\n```\n$ ENVFILE=.env.staging react-native run-ios           # bash\n$ SET ENVFILE=.env.staging \u0026\u0026 react-native run-ios    # windows\n$ env:ENVFILE=\".env.staging\"; react-native run-ios    # powershell\n```\n\nThis also works for `run-android`. Alternatively, there are platform-specific options below.\n\n#### Android\n\nThe same environment variable can be used to assemble releases with a different config:\n\n```\n$ cd android \u0026\u0026 ENVFILE=.env.staging ./gradlew assembleRelease\n```\nNote: When trying to release the bundle you need to export with a different config\n```\n$ cd android \u0026\u0026 export ENVFILE=.env.staging ./gradlew bundleRelease\n```\n\nAlternatively, you can define a map in `build.gradle` associating builds with env files. Do it before the `apply from` call, and use build cases in lowercase, like:\n\n```\nproject.ext.envConfigFiles = [\n    debug: \".env.development\",\n    release: \".env.production\",\n    anothercustombuild: \".env\",\n]\n\napply from: project(':react-native-config').projectDir.getPath() + \"/dotenv.gradle\"\n```\n\nAlso note that besides requiring lowercase, the matching is done with `buildFlavor.startsWith`, so a build named `debugProd` could match the `debug` case, above.\n\n\u003ca name=\"ios-multi-scheme\"\u003e\u003c/a\u003e\n\n#### iOS / macOS\n\nThe basic idea in iOS is to have one scheme per environment file, so you can easily alternate between them.\n\nStart by creating a new scheme:\n\n- In the Xcode menu, go to Product \u003e Scheme \u003e Edit Scheme\n- Click Duplicate Scheme on the bottom\n- Give it a proper name on the top left. For instance: \"Myapp (staging)\"\n- Make sure the \"Shared\" checkbox is checked so the scheme is added to your version control system\n\nThen edit the newly created scheme to make it use a different env file. From the same \"manage scheme\" window:\n\n- Expand the \"Build\" settings on left\n- Click \"Pre-actions\", and under the plus sign select \"New Run Script Action\"\n- Where it says \"Type a script or drag a script file\", type:\n  ```\n  cp \"${PROJECT_DIR}/../.env.staging\" \"${PROJECT_DIR}/../.env\"  # replace .env.staging for your file\n  ```\nAlso ensure that \"Provide build settings from\", just above the script, has a value selected so that PROJECT_DIR is set.\n\nAlternatively, if you have separated build configurations, you may easily set the different envfiles per configuration by adding these lines into the end of Podfile:\n\n```ruby\nENVFILES = {\n  'Debug' =\u003e '$(PODS_ROOT)/../../.env.debug',\n  'Release' =\u003e '$(PODS_ROOT)/../../.env.production',\n}\npost_install do |installer|\n  installer.pods_project.targets.each do |target|\n    target.build_configurations.each do |config|\n      if target.name == 'react-native-config'\n        config.build_settings['ENVFILE'] = ENVFILES[config.name]\n      end\n    end\n  end\nend\n```\n\nNote that if you have flipper enabled in your Podfile, you must move the `flipper_post_install` into the newely added hook since Podfile doesn't allow multiple `post_install` hooks.\n\n```diff\n  target 'MyApp' do\n    # ...\n    use_flipper!\n-   post_install do |installer|\n-     flipper_post_install(installer)\n-   end\n  end\n\n  post_install do |installer|\n+   flipper_post_install(installer)\n\n    installer.pods_project.targets.each do |target|\n      target.build_configurations.each do |config|\n        if target.name == 'react-native-config'\n          config.build_settings['ENVFILE'] = ENVFILES[config.name]\n        end\n      end\n    end\n  end\n```\n\n## Troubleshooting\n\n### Problems with Proguard\n\nWhen Proguard is enabled (which it is by default for Android release builds), it can rename the `BuildConfig` Java class in the minification process and prevent React Native Config from referencing it. To avoid this, add an exception to `android/app/proguard-rules.pro`:\n\n    -keep class com.mypackage.BuildConfig { *; }\n\n`com.mypackage` should match the `package` value in your `app/src/main/AndroidManifest.xml` file.\n\nIf using Dexguard, the shrinking phase will remove resources it thinks are unused. It is necessary to add an exception to preserve the build config package name.\n\n    -keepresources string/build_config_package\n\n### TypeError: _reactNativeConfig.default.getConstants is not a function\n\nThis error stems from `.env` file being malformed. Accepted formats are listed here https://regex101.com/r/cbm5Tp/1. Common causes are:\n  - Missing the .env file entirely\n  - Rogue space anywhere, example: in front of env variable: ` MY_ENV='foo'`\n\n## Testing\n\nSince `react-native-config` contains native code, it cannot be run in a node.js environment (Jest, Mocha). [react-native-config-node](https://github.com/CureApp/react-native-config-node) provides a way to mock `react-native-config` for use in test runners - exactly as it is used in the actual app.\n\nOn Windows, [the Example app](example/) supports running automatic tests by using [WinAppDriver](https://github.com/microsoft/WinAppDriver). In the Example app folder run:\n\n```console\nyarn appium\nyarn test:windows\n```\n\n### Jest\n\nFor mocking the `Config.FOO_BAR` usage, create a mock at `__mocks__/react-native-config.js`:\n\n```\n// __mocks__/react-native-config.js\nexport default {\n  FOO_BAR: 'baz',\n};\n```\n\n## Meta\n\nCreated by Pedro Belo at [Lugg](https://lugg.com/).\n","funding_links":[],"categories":["Components","\u003ca name=\"OS-\u0026-System-\u0026-File-Manager:-Native-Modules\"\u003eOS, System \u0026 File Manager: Native Modules\u003c/a\u003e","Index"],"sub_categories":["System","Configuration"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluggit%2Freact-native-config","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluggit%2Freact-native-config","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluggit%2Freact-native-config/lists"}