Why Use flutter_secure_storage Over shared_preferences for Storing PII in Flutter Apps

Ashutosh Agarwal
2 min readNov 4, 2024

--

When building Flutter apps, securely storing sensitive information like Personally Identifiable Information (PII) and authentication tokens is essential. While shared_prefernces is commonly used for key-value storage, it doesn’t offer the encryption or security needed for sensitive data. Data stored in `shared_preferences` is saved in plain text, making it vulnerable to unauthorized access if the device is compromised.

Why Not Use shared_preferences?

shared_prefernces is ideal for storing non-sensitive data, such as user preferences and settings, but it’s not secure for PII or tokens.

Sensitive data stored here can be accessed if someone gains access to the device, as shared_prefernceslacks encryption.

Why flutter_secure_storage Is Better for PII and Tokens

flutter_secure_storage is designed to securely store sensitive information by using:

  • iOS Keychain for iOS and Android Keystore for Android, offering strong encryption.
  • Automatic integration with platform security updates, which enhances data protection over time.

This makes flutter_secure_storage a better choice for securely storing items like user emails and auth tokens.

Quick Setup with flutter_secure_storage

  1. Add flutter_secure_storage to pubspec.yaml:
dependencies:
flutter_secure_storage: ^8.0.0
  1. Import and Use:
dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = FlutterSecureStorage();
// Store email and auth token
await storage.write(key: 'userEmail', value: 'user@example.com');
await storage.write(key: 'authToken', value: 'your_auth_token');
// Retrieve email and auth token
String? email = await storage.read(key: 'userEmail');
String? token = await storage.read(key: 'authToken');
// Delete sensitive data when no longer needed
await storage.delete(key: 'userEmail');
await storage.delete(key: 'authToken');

Best Practices

  • Store Only Essential PII: Minimize stored PII and tokens to only what is necessary.
  • Clear Data When Not Needed: Delete sensitive data when it’s no longer required.
  • Use Biometrics for Extra Security: Combine flutter_secure_storage with local_authto prompt for biometrics before accessing sensitive data.

Conclusion

For secure storage of PII and tokens, flutter_secure_storageis far safer than shared_prefernces. It leverages encryption and secure storage mechanisms native to iOS and Android, providing a reliable solution for protecting user data in your Flutter app.

--

--

No responses yet