expo-mobile-ads
v1.9.0
Published
Multi-mediation mobile ads module for Expo
Maintainers
Readme
expo-mobile-ads
Multi-mediation mobile ads module for Expo apps. One react-native-google-mobile-ads-compatible API in front of selectable mediation SDKs — currently AdMob (Google Mobile Ads) and DT FairBid — with the active mediation switchable at runtime.
- Build-time selection: the config plugin compiles in only the mediation SDKs and AdMob adapter networks you list. Unselected SDKs are not in the binary and never load.
- Runtime switching:
MobileAds().setMediation("fairbid")flips which SDK serves subsequently created ads — handy behind remote config. - Drop-in API:
InterstitialAd/RewardedAd/BannerAd/NativeAd/AdsConsent/AdEventType/TestIdsmirror react-native-google-mobile-ads, so call sites migrate mechanically. One deviation: rewarded events are folded intoAdEventType(LOADED,EARNED_REWARD) instead of a separateRewardedAdEventType.
Format support by mediation:
| Format | AdMob | FairBid | | --- | --- | --- | | Interstitial | ✅ | ✅ | | Rewarded | ✅ | ✅ | | Banner | ✅ | ✅ | | Native | ✅ | ❌ |
Installation
npx expo install expo-mobile-adsConfig plugin
// app.json
{
"expo": {
"plugins": [
[
"expo-mobile-ads",
{
"mediations": {
"admob": {
"androidAppId": "ca-app-pub-xxxxxxxx~xxxxxxxx",
"iosAppId": "ca-app-pub-xxxxxxxx~xxxxxxxx"
},
"fairbid": {
"androidAppId": "123456",
"iosAppId": "123457"
}
},
"networks": ["unity", "ironsource", "pangle"],
"userTrackingUsageDescription": "This identifier will be used to deliver personalized ads to you.",
"skAdNetworkItems": ["cstr6suwn9.skadnetwork"]
}
]
]
}
}| Option | Description |
| --- | --- |
| mediations | Mediation SDKs to compile in, keyed by mediation ("admob", "fairbid") with per-platform app ids. At least one is required — either alone works. AdMob requires both app ids; FairBid takes DT Console app ids and stays dormant without them. |
| mediations.admob.disableNativeAdValidator | Disables the AdMob native ad validator debug overlay on both platforms. (FairBid has no native ads or validator — its debug tool is FairBid.showTestSuite().) |
| networks | AdMob mediation adapters to compile in: bidmachine, bigo, dtexchange, inmobi, ironsource, liftoff, line, meta, pangle, unity. Defaults to none. Requires admob. |
| userTrackingUsageDescription | iOS ATT prompt copy. |
| skAdNetworkItems | Extra SKAdNetwork ids merged into Info.plist. |
Run npx expo prebuild after changing plugin options.
Usage
import MobileAds, { AdEventType, InterstitialAd, RewardedAd, TestIds } from "expo-mobile-ads";
// Optional, before initialize: pushes GDPR/CCPA consent signals to every SDK in
// the build (FairBid + adapter network SDKs such as Pangle, Unity, ironSource).
MobileAds().setConsent(true);
// Once at startup — initializes every mediation compiled into the build.
await MobileAds().initialize();
// Runtime mediation switch (e.g. driven by remote config).
if (MobileAds().isMediationSupported("fairbid")) {
MobileAds().setMediation("fairbid");
}
// The ad unit id belongs to the mediation serving the ad:
// an AdMob ad unit id, or a FairBid placement id when the mediation is "fairbid".
const ad = RewardedAd.createForAdRequest(TestIds.REWARDED, {
// Optional per-ad override of the global mediation.
mediation: "admob",
});
ad.addAdEventListener(AdEventType.LOADED, () => ad.show());
ad.addAdEventListener(AdEventType.EARNED_REWARD, (reward) => grant(reward));
ad.addAdEventListener(AdEventType.CLOSED, () => next());
ad.load();Ads are single-use: after AdEventType.CLOSED create a new instance to show again. AdEventType.PAID delivers impression-level revenue ({ currency, value, precision }) from both mediations.
Every show ends in CLOSED or ERROR. Some exits skip the SDK's own dismissal callback. On Android, relaunching from the launcher icon clears a singleTask activity's task and destroys the ad. On iOS, a mediation adapter can tear down its UI without forwarding the dismissal. When that happens, the module reports the end itself once the app is back in front and nothing the ad put on screen is left: on Android, the activities opened during the show are destroyed; on iOS, the view controllers that came on screen during the show, presented over the app or in a window of their own, are gone. iOS has no event for that, so the module checks when the app becomes active, when a window is hidden, and when the user touches the app. It first waits one second in case the SDK's callback is just late. It sends CLOSED when the ad had opened, and ERROR with code show-interrupted when it had not.
An ad that was loaded (or is still loading) but will never be shown — e.g. a losing attempt in a load waterfall — should be released with ad.destroy(), which drops its listeners and frees the natively retained ad. Shown ads clean up on their own after CLOSED.
Banner ads
import { BannerAd, BannerAdSize } from "expo-mobile-ads";
<BannerAd
unitId={TestIds.BANNER}
size={BannerAdSize.MEDIUM_RECTANGLE}
onAdLoaded={() => {}}
onAdFailedToLoad={(error) => {}}
onAdImpression={() => {}}
onAdClicked={() => {}}
onPaid={(event) => {}}
/>The view sizes itself from the loaded ad. iOS banners pause while the app is backgrounded, so the view automatically requests a fresh ad when the app returns to the foreground; a ref exposes load() for manual reloads. Under the FairBid mediation the size prop is ignored — the placement's DT Console configuration decides the banner size.
Native ads (AdMob only)
import { NativeAd, NativeAdView, NativeAsset, NativeAssetType, NativeMediaView } from "expo-mobile-ads";
const ad = await NativeAd.createForAdRequest(TestIds.NATIVE, {
aspectRatio: NativeMediaAspectRatio.LANDSCAPE,
adChoicesPlacement: NativeAdChoicesPlacement.BOTTOM_RIGHT,
});
<NativeAdView nativeAd={ad}>
<NativeAsset assetType={NativeAssetType.HEADLINE}>
<Text>{ad.headline}</Text>
</NativeAsset>
<NativeMediaView resizeMode="cover" style={{ height: 160 }} />
</NativeAdView>NativeAdView makes the entire ad area clickable (a tracking overlay covers the rendered assets), so keep interactive app controls outside of it. When the active mediation has no native format (FairBid), createForAdRequest rejects immediately — fall back the same way you handle a no-fill.
AdMob debugging
MobileAds().setLineTestMode(true); // before initialize: the LINE adapter serves test ads
await MobileAds().openAdInspector(); // pick one mediated ad source for every requestThe Ad Inspector only opens on AdMob test devices; its single ad source testing is the way to see a specific network's creative (e.g. a LINE native ad for a design review). setLineTestMode does nothing unless the line network is in the build — never ship it enabled.
FairBid utilities
import { FairBid } from "expo-mobile-ads";
FairBid.setUserId("hashed-user-id"); // for server-side rewarding callbacks
FairBid.showTestSuite(); // inspect mediated network integrationsFairBid keeps placements auto-refilled after the first request, so a second load() for the same placement usually resolves instantly.
Consent (UMP)
AdsConsent wraps Google's User Messaging Platform, which shows the messages published under AdMob → Privacy & messaging for the AdMob app id (e.g. European regulations for EEA/UK/Switzerland). It is available whenever the admob mediation is included; every call throws otherwise.
import MobileAds, { AdsConsent, AdsConsentPrivacyOptionsRequirementStatus } from "expo-mobile-ads";
// Consent from the previous session can request ads while UMP checks for updates.
if ((await AdsConsent.getConsentInfo()).canRequestAds) {
MobileAds().initialize();
}
// On every launch: refresh consent and show the form when required.
const info = await AdsConsent.gatherConsent();
if (info.canRequestAds) {
MobileAds().initialize();
}
// Settings entry point, required where a message applies.
if (info.privacyOptionsRequirementStatus === AdsConsentPrivacyOptionsRequirementStatus.REQUIRED) {
await AdsConsent.showPrivacyOptionsForm();
}Request no ads until canRequestAds is true. It stays true after the user rejects consent — UMP writes the choice to the IAB TC string, which AdMob and the mediation adapters read on their own — so it permits requests, not personalization. Also available: requestInfoUpdate and loadAndShowConsentFormIfRequired (the two halves of gatherConsent).
Consent updates and form calls wait while the app is in the background and continue when it returns to the foreground. This also applies when the app backgrounds between the two steps of gatherConsent.
To test a regulated region, pass the hashed device id the UMP SDK logs on first run, and clear the stored choice between runs:
import { AdsConsent, AdsConsentDebugGeography } from "expo-mobile-ads";
await AdsConsent.reset(); // testing only
await AdsConsent.gatherConsent({
debugGeography: AdsConsentDebugGeography.EEA,
testDeviceIdentifiers: ["HASHED_DEVICE_ID"],
});Network consent signals
MobileAds().setConsent(consent) fans the user's privacy choice out to every SDK compiled into the build — call it before initialize when possible. Where UMP shows a message, let the adapters read the TC string instead of hard-coding a value (e.g. only call setConsent(true) when AdsConsent reports NOT_REQUIRED). Per network:
| SDK | Signal |
| --- | --- |
| FairBid | GDPR consent (iOS only supports granting; false is a no-op) |
| Pangle | PA consent |
| Liftoff | CCPA status |
| Meta | Advertiser tracking enabled (iOS only) |
| Unity | gdpr.consent + privacy.consent metadata |
| DT Exchange | US privacy string (1YNN / 1YYN) |
| ironSource | GDPR consent + CCPA flag (LevelPlayPrivacySettings / LPMPrivacySettings) |
| BIGO | CCPA consent (GDPR is read from the UMP TC string) |
Networks not compiled into the build — and networks without a consent API (InMobi, LINE) — are skipped. AdMob itself is unaffected; handle it with AdsConsent or requestNonPersonalizedAdsOnly.
How build-time selection works
- Android: the mediation SDKs are
compileOnlydependencies of the module; the config plugin adds the realimplementationdependencies (and any Maven repositories) to your app for the selected mediations/networks only. Presence is detected withClass.forNameat runtime. - iOS: the plugin records the selected mediations and networks in
Podfile.properties.json; the podspec adds the matching SDK and adapter pods, and the Swift sources compile out via#if canImport.
MobileAds().supportedMediations reports what ended up in the binary.
R8
The module ships consumer keep rules (android/proguard-rules.pro) for every mediation SDK and network, so minified release builds need no extra rules in the app. Keep resource shrinking off: ad SDKs can resolve resources dynamically.
Pangle's own rules contain -ignorewarnings, which hides missing classes in every library of the app. When pangle is selected, the plugin adds optimization.keepRules.ignoreExternalDependencies("com.pangle.global:pag-sdk-ad") to android/app/build.gradle and the module's rules carry Pangle's keep rules instead, so R8 fails the build on missing classes again.
Example app
cd example
pnpm install
pnpm ios # or: pnpm androidVersions
| Dependency | Version |
| --- | --- |
| Google Mobile Ads Android (play-services-ads) | 25.2.0 |
| Google Mobile Ads iOS (Google-Mobile-Ads-SDK) | 13.7.0 |
| Google UMP Android (user-messaging-platform, via play-services-ads) | 4.0.0 |
| Google UMP iOS (GoogleUserMessagingPlatform) | 3.1.0 |
| DT FairBid (Android/iOS) | 3.67.0 |
The FairBidSDK pod pins Fyber_Marketplace_SDK exactly, so when both fairbid and the dtexchange network are enabled the plugin pins GoogleMobileAdsMediationFyber to the release built on the same marketplace version. Bump these together (see plugin/src/index.ts).
