Remote Feature Flagging is a development technique that allows developers to control the release of new features in their applications or services to a targeted group of users.
The concept behind feature flagging is to deploy code changes to production but only enable those features for specific users, groups of users or in certain environments. This allows developers to test new features with a smaller set of users before rolling them out to the entire user base.
Remote feature flagging can be implemented in various ways, but typically, it involves creating a configuration file that contains a set of flags, each representing a specific feature. These flags can be turned on or off remotely without deploying new code.
With remote feature flagging, developers can:
- Gradually release new features to users in a controlled manner.
- Test features with a smaller group of users to gather feedback and ensure they are functioning as expected.
- Rollback features that are causing issues or negative user experiences.
- Gather analytics on how users are interacting with features, which can inform future development decisions.
Overall, remote feature flagging is a powerful tool for software development teams to iterate quickly, minimise risk, and improve the user experience.
Firebase Remote Config is a cloud-based service provided by Google Firebase that allows developers to implement remote feature flagging in their applications. Firebase Remote Config enables developers to change the behaviour and appearance of their applications without requiring a new app release.
To use Firebase Remote Config for remote feature flagging, you will need to perform the following steps:
- Integrate Firebase into your application: Before you can use Firebase Remote Config, you will need to integrate Firebase into your application. This involves adding the Firebase SDK to your project and configuring it.
- Define feature flags: Once Firebase is integrated, you can define feature flags in Firebase Remote Config. These feature flags can be turned on or off remotely, allowing you to control which features are available to specific users or groups.
- Update feature flags: Once feature flags are defined, you can update them remotely from the Firebase console. This enables you to release new features to a subset of users, test them, and gradually roll them out to a larger audience.
- Fetch feature flags: Finally, you can fetch the latest feature flag configuration from Firebase Remote Config in your application. Based on the state of the feature flags, you can enable or disable specific features or change their behaviour.
By using Firebase Remote Config for remote feature flagging, you can avoid the need for a new app release for every feature change. This helps you to iterate quickly, gather feedback, and improve the user experience more efficiently.
In this tutorial, you’ll learn how to use Firebase to implement remote feature flagging in a React Native app.
Setting up Firebase
The first step is to create a Google account if you don’t have one yet.
Then, go to the Firebase website (https://console.firebase.google.com) and create a new project in the Firebase console with following steps.
- Enable Firebase Remote Config and Google Analytics for the project.
Generating a Private Key
To use Firebase in your React Native app, you’ll need to generate a private key for admin access.
This can be done in the Firebase console. Follow the step-by-step instructions in this section to generate the key.
Then a json file with your credential will be downloaded. Store the key at safe place and never expose to public.
Creating a React Native App
To get started with your React Native app, you’ll need to have Node.js and React Native CLI installed on your computer.
Follow the step-by-step instructions (https://reactnative.dev/docs/environment-setup) in this section to create a new React Native app.
npx react-native init FeatureFlagging --template react-native-template-typescript
Then we created a react native project with typescript template.
Adding User Login Function
In order to use remote feature flagging to control content for specific users, you’ll need to identify them using user login.
We can add a userEffect
hook to your React Native app and ask for their email as the user ID.
const [email, setEmail] = useState('');
useEffect(() => {
const showAlert = () => {
Alert.prompt(
'Email Address',
'Please enter your email address:',
(inputEmail: string) => {
setEmail(inputEmail);
},
);
};
And update the ScrollView
to display a email section only
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Section title={email} />
</View>
</ScrollView>
</SafeAreaView>
Integrating Firebase SDK
Firebase provides SDKs that can be used to integrate Firebase services into your app.
Follow the step-by-step instructions in this section to add the Firebase SDK to your React Native app.
- Create a new iOS app on the Firebase console
Pay attention that this is just one approach to integrate Firebase SDK into a React Native App and there are several other ways as well.
- Download the
GoogleService-Info.plist
file and put in the ./ios directory - Follow the
See SDK instructions
to add following code into./ios/FeatureFlagging/AppDelegate.mm
#import "Firebase.h"
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
return YES;
}
- Add
GoogleService-info.plist
to the iOS project - Add following node modules as the dependencies in the
Package.json
"@react-native-firebase/analytics": "^17.3.1",
"@react-native-firebase/app": "^17.3.1",
- Add following key to
Info.plist
file in the ios project
<key>FirebaseCore</key>
<dict>
<key>APIKey</key>
<string>your APIKey</string>
<key>GoogleAppID</key>
<string>your GoogleAppID</string>
<key>ProjectNumber</key>
<string>your ProjectNumber</string>
</dict>
The APIKey is generated in previous step, the GoogleAppID and ProjectNumber can be found at the Firebase console.
- Install dependencies with
yarn install
cd ios
pod repo update
pod install
cd ..
- Build the app with
react-native run-ios
- Might need to add following code the
PodFile
if failed to build the app
use_modular_headers!
use_frameworks! :linkage => :static
Then we should see the app running on the iOS simulator
- To send example analytic event from the app, we can update following code in the
useEffect
in theApp.tsx
like
import analytics from '@react-native-firebase/analytics';
...
useEffect(() => {
const showAlert = () => {
Alert.prompt(
'Email Address',
'Please enter your email address:',
async (inputEmail: string) => {
setEmail(inputEmail);
await analytics().setUserProperty('email', inputEmail);
},
);
};
...
Then if we build and run the app again, the app will send a user property with following value to the Google Analytics
{
email: inputEmail
}
This user property will be logged by Google Analytics and provided to Google Remote Config as the user identity.
Adding Feature Flags
In this section, you’ll learn how to define feature flags in your React Native app and use remote config to fetch them from Firebase.
Follow the step-by-step instructions in this section to define feature flags and display different content based on the remote config fetched from Firebase.
Let us try to add new feature flag on Firebase Remote Config manually first
- Go to Firebase console and go to Remote Config
- Click
Create Configuration
to create a new parameter, including name, type and default value
- Then we can see this parameter like
Don’t forget publish changes
Integrate Firebase Remote Config into the App with following steps
- Install dependency
yarn add @react-native-firebase/remote-config
cd ios
pod install
cd ..
- Update the
App.tsx
like
...
import remoteConfig, {
FirebaseRemoteConfigTypes,
} from '@react-native-firebase/remote-config';
...
const [featureFlags, setFeatureFlags] =
useState<FirebaseRemoteConfigTypes.ConfigValues>({});
...
useEffect(() => {
const showAlert = () => {
Alert.prompt(
'Email Address',
'Please enter your email address:',
async (inputEmail: string) => {
setEmail(inputEmail);
await analytics().setUserProperty('email', inputEmail);
setTimeout(async () => {
await remoteConfig().fetch(0);
await remoteConfig().activate();
const config = remoteConfig().getAll();
setFeatureFlags(config);
}, 1000);
},
);
};
showAlert();
}, []);
...
<Section title={email}>
{JSON.stringify(featureFlags, undefined, 4)}
</Section>
Add a new state featureFlags
to store the remote config from the Firebase. Call remoteConfig().fetch()
, remoteConfig().activate()
and remoteConfig().getAll()
functions to fetch the remote config and update the state. Display the remote config object in a section
- Build and run
react-native run-ios
The app looks like
We have integrated the Firebase remote config into the app and fetched the preset value. Let’s try making Firebase remote config to return different value base on the user identity in next chapter.
Logging User Properties with Google Analytics
You can use Firebase Remote Config to set conditions and return different values based on those conditions.
This condition is based on the user property like
- The Admin adds a remote config condition with some user properties
- The Admin adds a remote config parameter with this condition
- The User sends user property to Google Analytics
- The User fetches the remote config from the Firebase remote config
- The Firebase remote config queries the user property from Google Analytics
- The Firebase remote config returns correct value based on the condition
Setting a Condition on Firebase Remote Config
Follow the step-by-step instructions in this section to set a condition on Firebase Remote Config console and see the changes in your React Native app.
- Add condition
Firebase Remote Config supports multi types of condition. We set the condition here with checking if the user propertyemail
is user1
or user2
.
- Update the remote config parameter
Then we make the remote config returns true if condition feature flag condition
matches, or else false.
- We can check the parameter is updated like
- Don’t forget to publish the changes
- Run the app and input different user email / ID, we would get different value from the Firebase Remote Config.
Setting parameter / conditions on Remote Config programmatically
We tried to set remote config parameter / conditions on the Firebase console in above chapter and it works well. Then we can also setup them programmatically with Firebase SDK. Then we ca n write some app / script / web service to setup remote config parameter / conditions.
The following code snippet is an example about how to build up a web service with nodejs for setting up Firebase Remote Config parameter / conditions.
The <credential.json> is the json file downloaded in above chapter, and the databaseURL and projectId can be found from the Firebase console.
const express = require('express');
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
const serviceAccount = require('./<credential.json>');
const app = express();
app.use(bodyParser.json());
// Initialize Firebase app
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: '<databaseURL>',
projectId: '<projectId>',
});
app.post('/set-feature-flag', async (req, res) => {
try {
const remoteConfig = admin.remoteConfig();
const template = await remoteConfig.getTemplate();
const featureFlags = req.body;
for (const [key, value] of Object.entries(featureFlags)) {
const featureFlag = key.toUpperCase();
const emailString =
'^(' +
value.condition.emails
.map(email => `${email.toUpperCase()}`)
.join('|') +
')$';
const newCondition = {
name: `${featureFlag} Segment`,
expression: `app.userProperty['user_email'].matches(['${emailString}'])`,
};
const index = template.conditions.findIndex(
condition => condition.name === newCondition.name,
);
index >= 0
? (template.conditions[index] = newCondition)
: template.conditions.push(newCondition);
template.parameters[`FEATURE_FLAG_${featureFlag}`] = {
defaultValue: {value: 'false'},
conditionalValues: {
[`${newCondition.name}`]: {value: 'true'},
},
valueType: 'BOOLEAN',
};
}
const updatedTemplate = await remoteConfig.createTemplateFromJSON(
JSON.stringify(template),
);
// console.log(JSON.stringify(template.parameters, undefined, 4))
const newTemplate = await remoteConfig.publishTemplate(updatedTemplate);
// res.json({ success: true, message: 'Audience segment created successfully' });
res.json(newTemplate.conditions);
} catch (error) {
console.error(error);
res
.status(500)
.json({success: false, message: 'Failed to create feature flag'});
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Conclusion
- Congratulations! You’ve successfully implemented remote feature flagging in your React Native app with Firebase.
- Remote feature flagging is a powerful tool that allows you to control app features and content remotely without requiring app updates.
- With Firebase, you can easily configure and manage remote feature flags for your app.