Repository navigation
Facebook Instant Games
Instant Games run inside the Facebook app on iOS and Android, and on the web at facebook.com/gaming. Players can also discover and start them from Messenger conversations.
This guide covers melonJS 20.15 or later with Instant Games SDK 8.0, the current version. See Platforms for the pattern shared with the other portals.
There are four steps:
- Create an Instant Game app in your Meta developer account
- Add the SDK to your game, and connect it to melonJS
- Try the game locally, then in Facebook's player
- Upload it
Sign in to your Meta developer account, create a new app of the "Games" type, and set it up as an Instant Game. Follow the on-screen steps.
Facebook loads index.html from the root of your upload, next to a required fbapp-config.json.
Load the SDK from Facebook's CDN, before your game. Don't copy it into your bundle: Facebook rejects bundles that include it.
<div id="screen"></div>
<!-- the Instant Games SDK, before the game -->
<script src="https://connect.facebook.net/en_US/fbinstant.8.0.js"></script>
<script type="module" src="index.js"></script>A minimal fbapp-config.json (with Vite, put it in public/ so the build copies it next to index.html):
{
"instant_games": {
"navigation_menu_version": "NAV_BAR",
"orientation": "PORTRAIT"
}
}navigation_menu_version is required, and the values are case-sensitive. See Bundle Configuration for the other options.
FBInstant.initializeAsync() must resolve before anything else calls the SDK. After that, the game loads while Facebook shows its own loading screen, and startGameAsync() hands the screen over to the game:
import { Application, device, event, loader, state, video } from "melonjs";
import { PlayScreen } from "./screens/play.js";
import { resources } from "./resources.js";
import { useFacebookSave } from "./facebook-save.js";
// nothing else may call the SDK before this resolves
await FBInstant.initializeAsync();
const app = new Application(360, 640, {
parent: "screen",
scaleMethod: "fit",
renderer: video.AUTO,
});
// Facebook says when the game is in the foreground, not the browser window
device.setFocusEvents(false);
app.stopOnBlur = true;
app.pauseOnBlur = false;
FBInstant.onPause(() => event.emit(event.BLUR));
FBInstant.onResume(() => event.emit(event.FOCUS));
await app.init();
await useFacebookSave();
// Facebook draws the loading screen: tell it how far along the game is
event.on(event.LOADER_PROGRESS, (progress) => {
FBInstant.setLoadingProgress(Math.round(progress * 100));
});
await loader.preload(resources);
state.set(state.PLAY, new PlayScreen());
await FBInstant.startGameAsync();
state.change(state.PLAY, true);If the canvas comes up at the wrong size once the game starts, call app.resize() after startGameAsync() resolves.
Facebook calls onPause when the player switches to another tab or app, and onResume when they come back. The code above hands those to melonJS:
-
device.setFocusEvents(false)decides who reports that the player left: Facebook, rather than the browser window. - The
pauseOnBlur,stopOnBlurandresumeOnFocusflags decide what the game does about it. WithstopOnBlur, melonJS stops the game loop and the rendering, pauses the music, mutes the sound effects and releases held keys, then undoes exactly that on resume.
Leaving the flags at their defaults and the window in charge also works: Facebook's events just make Facebook the one source, the same in the app and on the web.
Instant Games keep up to 1 MB of data per player in Facebook's cloud, with FBInstant.player.getDataAsync() and setDataAsync(). melonJS's save can keep its keys there instead of in localStorage: load them once, then hand save a storage made by save.createCloudStorage():
// facebook-save.js
import { save } from "melonjs";
export async function useFacebookSave() {
const { save: data } = await FBInstant.player.getDataAsync(["save"]);
save.setStorage(save.createCloudStorage({
data,
write: (items) => FBInstant.player.setDataAsync({ save: items }),
}));
}The storage keeps everything in memory and saves it to Facebook in the background, one save at a time: Facebook refuses a save while another is still pending (PENDING_REQUEST), so the changes made in the meantime go in the next one. The rest of the game just uses save, as it would anywhere else:
const progress = save.add({ level: 1, best: 0 }); // the saved values, or these defaults
progress.best = 4200; // saved to the player's Facebook cloudsetDataAsync() resolves once the save is scheduled; Facebook writes it a little later. For data that can't be lost, such as a purchase, FBInstant.player.flushDataAsync() forces the write, but it is slow, so keep it for those.
FBInstant.getLocale() returns the player's locale once initializeAsync() has resolved, with an underscore: "en_US", "fr_FR". Turn it into a language tag with FBInstant.getLocale().replace("_", "-").
Ads use the placement IDs from your app's Monetization Manager:
// an interstitial, between two levels
const ad = await FBInstant.getInterstitialAdAsync("YOUR_PLACEMENT_ID");
await ad.loadAsync();
await ad.showAsync();
// a rewarded video: give the reward once showAsync() resolves
const rewarded = await FBInstant.getRewardedVideoAsync("YOUR_PLACEMENT_ID");
await rewarded.loadAsync();
await rewarded.showAsync();Wrap them in try / catch: no ad being available is normal, and the game should carry on. Banner ads are being phased out, and will be removed on 31 March 2027.
SDK 8.0 follows Meta's "Zero Permissions" model, and FBInstant.player.getName() and getPhoto() are gone. Code written for an older SDK that calls them stops with a TypeError. Facebook now shows players' names and photos itself, through overlay views. FBInstant.player.getID() still returns an ID for the player, specific to your game.
The SDK loads anywhere, but outside Facebook initializeAsync() never resolves: the game waits on a blank page. To develop locally, give the game a stand-in for the SDK when it isn't running in Facebook's player. Facebook always runs a game in a frame, so a page that isn't in one gets the stand-in:
// fbinstant-dev.js: import it first in your main file
if (window.self === window.top) {
const pause = [];
const resume = [];
globalThis.FBInstant = {
initializeAsync: async () => {},
setLoadingProgress: (percent) => console.debug(`loading ${percent}%`),
startGameAsync: async () => {},
getLocale: () => navigator.language.replace("-", "_"),
onPause: (callback) => pause.push(callback),
onResume: (callback) => resume.push(callback),
player: {
// the "cloud" is localStorage while developing
getDataAsync: async (keys) => {
const all = JSON.parse(localStorage.getItem("fbinstant-dev") ?? "{}");
return Object.fromEntries(keys.filter((k) => k in all).map((k) => [k, all[k]]));
},
setDataAsync: async (data) => {
const all = JSON.parse(localStorage.getItem("fbinstant-dev") ?? "{}");
localStorage.setItem("fbinstant-dev", JSON.stringify({ ...all, ...data }));
},
},
getInterstitialAdAsync: async () => ({ loadAsync: async () => {}, showAsync: async () => {} }),
getRewardedVideoAsync: async () => ({ loadAsync: async () => {}, showAsync: async () => {} }),
};
// try pausing from the console: fbinstantDev.pause(), fbinstantDev.resume()
globalThis.fbinstantDev = {
pause: () => pause.forEach((callback) => callback()),
resume: () => resume.forEach((callback) => callback()),
};
}It only covers what the game above uses. Social features, payments and real ads need Facebook's player.
Facebook can run your local build in its real player, with the real SDK:
- Serve the game over HTTPS on port 8080. With a self-signed certificate:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes npx http-server dist -S -C cert.pem -K key.pem -p 8080
- Open
https://localhost:8080once and accept the certificate warning. - Open
https://www.facebook.com/embed/instantgames/YOUR_APP_ID/player?game_url=https://localhost:8080, logged in with an account that has a role on the app.
See Meta's Game Testing page for the details.
Facebook hosts the game: no server of your own is needed.
- Build the game, then zip the contents of the build folder, so that
index.htmlandfbapp-config.jsonare at the root of the zip, not in a sub-folder. The zip can be up to 400 MB, but keep what loads first under 5 MB. - In the App Dashboard, open "Instant Games" > "Web Hosting".
- Click "+ Upload Version" and upload the zip.
- When the version shows "Standby", click "★" to push it to production.
More on testing, publishing and sharing: Test, Publish and Share.