Securing sensitive keys in React Native with React Native config
10/8/20244 min read
Introduction
In today’s world, mobile apps are not only tools for convenience but also gateways to sensitive data. As mobile app developers, one of our key responsibilities is to ensure that this data remains safe. A common issue developers face is exposing sensitive information like API keys or configuration data in the app’s codebase. This can lead to serious security breaches, especially in open-source projects.
In React Native, this problem becomes critical because the app’s code can be easily reverse-engineered, making it possible for someone to extract sensitive information from it. Therefore, hiding API keys and other sensitive configuration data is essential to ensure the security of your mobile application. One way to do this in React Native is by using the react-native-config package.
Introducing React Native Config
React Native Config is a library that helps you manage environment-specific configuration variables. You can define variables such as API keys, database URLs, or any other settings in an environment file (usually .env), and these values will be injected into your app at build time. This way, sensitive data remains hidden and can vary between development, staging, and production environments.
How to Implement React Native Config
Let’s dive into a step-by-step guide on how to use React Native Config in a React Native project. We will hide an API key and make a request to a property website’s API.
Step 1: Install React Native Config
First, you need to install the react-native-config package. You can do this by running the following command in your project:
npm install react-native-config
For iOS, you might also need to run:
cd ios/ && pod install && cd ..
Step 2: Create an Environment File
Next, create a .env file at the root of your project. This file will contain your environment variables, including your API key.
// .env
API_PROPERTY_LIST=<your api route>
In this example, we’re defining a constant API_PROPERTY_LIST, which stores the URL to a property website's API endpoint for fetching property listings.
Step 3: Access Environment Variables in Your App
You can access these environment variables in your code through the Config object provided by react-native-config.
// src/app.tsx
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import Config from 'react-native-config';
// Define the API route using the environment variable
const API_PROPERTY_LIST = Config.API_PROPERTY_LIST;
const App: React.FC = () => {
const [properties, setProperties] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchProperties = async () => {
try {
const response = await fetch(API_PROPERTY_LIST);
const data = await response.json();
setProperties(data);
} catch (error) {
console.error('Error fetching property data:', error);
} finally {
setLoading(false);
}
};
fetchProperties();
}, []);
return (
<View>
{loading ? (
<Text>Loading...</Text>
) : (
<FlatList
data={properties}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.price}</Text>
</View>
)}
/>
)}
</View>
);
};
export default App;
Step 4: Secure Your .env File
To ensure that your .env file is not exposed to the public (especially in open-source projects), make sure to add it to your .gitignore file:
// .gitignore
.env
How React Native Config Works Under the Hood
To understand how react-native-config helps hide sensitive information, let’s take a look at what happens behind the scenes:
Environment Variables Parsing:
The react-native-config library reads the .env file during the build process.
It parses the file and transforms each key-value pair into accessible environment variables.
These variables are injected into the native build files (like iOS Info.plist or Android build.gradle), making them available at runtime.
Native Integration:
For iOS, the .env variables are added to the Xcode project as build settings. These settings can be referenced in Info.plist or other configuration files during the build phase.
For Android, the environment variables are included in the gradle.properties file and made accessible through Java code, allowing them to be used in the app’s logic.
Bridge to JavaScript:
Once the environment variables are set in the native layers (iOS and Android), they are exposed to the JavaScript runtime through a Config object.
This bridge between the native layer and JavaScript allows React Native to access the variables safely in the app code.
Build-Time Embedding:
Since these variables are injected at build time, they are not included in the app’s JavaScript bundle.
This ensures that sensitive information, such as API keys, is not exposed in the final code that gets deployed to users.
Environment-Specific Configuration:
You can create different .env files for various environments like .env.development, .env.staging, and .env.production.
Based on the build command (e.g., npm run build -- --configuration=production), react-native-config loads the appropriate environment file and applies the variables specific to that environment.
Accessing Variables:
The library reads the variables and exposes them in your JavaScript code via Config. These variables are loaded at runtime and only available in the code that explicitly uses them.
By handling variables this way, react-native-config ensures sensitive data is hidden, and you can easily manage different configurations for different environments
Conclusion
Using react-native-config, you can easily manage and secure sensitive configuration data such as API keys. This method not only improves your app’s security but also allows for easy environment management (e.g., development, staging, production). Always remember to keep your .env file out of version control to prevent any accidental leaks of sensitive data. With these simple steps, you're now able to securely fetch data from an API without exposing your API keys to the world.
By following this guide, you’re taking a big step toward protecting your app and its users from potential security threats!
If you need to integrate Advanced functionalities in your Mobile app, create one from scratch, or need consulting in react native. Visit the casainnov.com, and check their mobile app page, and contact them there.
#ReactNative #WebSockets #RealTime #MobileDevelopment #AppDevelopment