API key security
- React Native course
- Expert
- Lesson 38/47
- 5 min
Learn API key and secret management.
API key security
When API keys are embedded in the app they can be pulled out through reverse engineering. Obfuscation makes it harder but does not stop it. That is why keys should be carried through environment variables, not hardcoded.
In React Native you use react-native-dotenv or react-native-config. The key lives in a .env file; this file goes into .gitignore. The code reads it with process.env.API_KEY. In production the key is still bundled; but it is not visible in source. The safest path is to keep the key on a backend proxy and have the app call that proxy.
Using react-native-dotenv
With react-native-dotenv the variables in the .env file are brought into code. You write API_KEY=abc123 in the .env file. In code you take it with import { API_KEY } from '@env'.
This method separates the key from source. Teammates share a template .env.example file; everyone writes their own .env. In CI the env vars come from the pipeline. Remember: in production the key is still bundled; for full protection use a backend proxy. Still, if the source leaks the key cannot be read directly.
Practice Read the API key from an env variable
Write an apiClient.js skeleton. Import API_KEY from the '@env' module. Assign it to a const apiKey variable. Use it in an Authorization header in a fetch call.
Starter code
// Import API_KEY from the @env module
const apiKey = null; // replace with API_KEY
function fetchProfile() {
// add apiKey to the Authorization header
return fetch('https://api.example.com/profile');
}Sample solution
import { API_KEY } from '@env';
const apiKey = API_KEY;
function fetchProfile() {
return fetch('https://api.example.com/profile', {
headers: { Authorization: 'Bearer ' + apiKey }
});
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each flow piece to its role
| Term | Meaning |
|---|---|
react-native-dotenv |
Env library |
.env |
Key file |
.gitignore |
Hides the file |
process.env |
Reads in code |
2 Reading an env variable
import { ____ } from '@env';
import { API_KEY } from '@env';
Explanation: API_KEY is imported from the @env module.
3 Where is the .env file added?
.env- To package.json
- To .gitignore Correct answer
- To app.json
- To App.js
Explanation: The .env file goes into .gitignore; it never enters the repo.