How to Securely Access Private API Tokens in Flutter
When working with private APIs, hardcoding sensitive information like API tokens in your Flutter code is a serious security risk. If your code is pushed to a public repository, anyone can access your credentials, leading to unauthorized access and security breaches.
In this guide, you'll learn how to securely store and access private API tokens using environment variables in Flutter.
🔥 Why You Should Never Hardcode API Tokens
If your API token is exposed, malicious users can:
Gain unauthorized access to your services
Consume your API quota
Expose private data
Exploit security vulnerabilities
To prevent this, it's essential to store credentials outside of your source code using environment variables.
✅ Secure API Keys Using flutter_dotenv
The flutter_dotenv
package allows you to securely manage environment variables by loading them from a .env
file at runtime.
1️⃣ Install flutter_dotenv
Run the following command in your terminal:
flutter pub add flutter_dotenv
2️⃣ Create a .env
File
Create a .env
file in the root directory of your project. This file will store your sensitive credentials:
GITHUB_USERNAME=your_github_username
GITHUB_TOKEN=your_personal_access_token
⚠️ Important: Add .env
to your .gitignore
file to prevent it from being committed to Git.
3️⃣ Access Environment Variables in Code
Now, modify your constants file to use flutter_dotenv
:
import 'package:flutter_dotenv/flutter_dotenv.dart';
final String GITHUB_USERNAME = dotenv.env['GITHUB_USERNAME'] ?? '';
final String GITHUB_TOKEN = dotenv.env['GITHUB_TOKEN'] ?? '';
4️⃣ Load .env
in main.dart
Before accessing the environment variables, load them at the start of your application:
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter/material.dart';
void main() async {
await dotenv.load();
runApp(MyApp());
}
🎯 Benefits of Using flutter_dotenv
🔒 Prevents accidental leaks – Your API keys stay private and secure.
⚡ Easy to manage – Modify credentials without changing the source code.
🚀 Better security practices – Keeps secrets out of version control.
By following this approach, you ensure your API tokens remain safe while keeping your Flutter application secure and scalable.