Facebook SDK for JavaScript: Setup, Login and Graph API
The Facebook SDK for JavaScript (often called the Facebook JS SDK or FB SDK) is Meta's free browser library, loaded from connect.facebook.net, that adds Facebook Login, the Share dialog, social plugins and Graph API calls to a website. To use it you create an app at Meta for Developers, load sdk.js with your App ID, call FB.init with a Graph API version, and then use FB.login, FB.getLoginStatus and FB.api. Below are the exact steps, working code, the setup details that usually cause errors, and which social features still exist (the Like button and Comments plugin don't), current as of October 2026.
What is the Facebook SDK?
"Facebook SDK" is a family of official libraries for calling Meta's platform from different environments:
| SDK | For | Typical use |
|---|---|---|
| JavaScript SDK | Websites | Login, Share dialog, Graph API calls |
| Android SDK / iOS SDK | Native mobile apps | Login, sharing, app events |
| Unity SDK | Games | Login, sharing, app events |
| Business SDKs (Node.js, Python, PHP, Java) | Servers | Marketing API, Conversions API |
This article is about the JavaScript SDK for the browser. It runs entirely client-side and talks to the Graph API, Meta's HTTP API for reading and writing Facebook data. Meta doesn't publish the browser SDK as an official npm package or open source GitHub repository; it is only served from connect.facebook.net. Packages on npm that wrap it (for React, for example) are community-maintained, so check when they were last updated.
What the JavaScript SDK does not do
Older articles list ads, analytics and payments as "SDK features". As of October 2026:
- Ads and conversion tracking use the Meta Pixel (
fbevents.js, a separate script) and the server-side Conversions API, notsdk.js. - Facebook Analytics was shut down on June 30, 2021. Use Meta Events Manager for Pixel and app event data.
- Payments aren't part of the JavaScript SDK. Take payments on your site with a normal payment provider.
What is connect.facebook.net?
connect.facebook.net is Meta's domain for serving its browser scripts. https://connect.facebook.net/en_US/sdk.js is the JavaScript SDK (the en_US part sets the language of dialogs and buttons), and the Meta Pixel loads fbevents.js from the same domain. If you see requests to it in your network tab, a page is loading one of those scripts. Many ad blockers and privacy settings block this domain, which matters for your app (see Limitations).
Step 1: Create a Meta app
- Go to developers.facebook.com, log in, and open My Apps > Create App.
- Choose the use case for authenticating users with Facebook Login, and finish the wizard.
- Copy the App ID from the app dashboard. The App ID is public; the App Secret is not and must never appear in browser code.
- In the Facebook Login settings for your app (web login docs):
- Set Login with the JavaScript SDK to Yes.
- Add your site's domain to Allowed Domains for the JavaScript SDK.
- Add your URLs to Valid OAuth Redirect URIs.
- While the app is in Development mode, only people with a role on the app (admins, developers, testers) can log in. Switch it to Live when you launch; this requires a privacy policy URL and the other basic settings.
The public_profile and email permissions don't need App Review and are granted to all apps using Facebook Login. Anything beyond those requires App Review.
Step 2: Load and initialize the SDK
Meta's quickstart loads the SDK asynchronously right after the opening body tag so it doesn't block rendering. Define window.fbAsyncInit first; the SDK calls it once it has loaded:
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR_APP_ID',
cookie: true, // lets your server read the session
xfbml: true, // parse social plugins on the page
version: 'v26.0'
});
FB.getLoginStatus(handleStatus);
};
</script>
<script async defer crossorigin="anonymous"
src="https://connect.facebook.net/en_US/sdk.js"></script>
The version parameter is required. It pins the Graph API version your calls use. As of October 2026 the newest is v26.0 (released July 29, 2026); each version stays available for at least two years, and the Graph API changelog lists expiry dates (v24.0 expires February 18, 2028, for example). Use the newest version for new apps and plan an upgrade before yours expires.
In a single-page app (React, Vue, Svelte), load the script once, and wrap it in a promise so components can wait for it:
// facebook.js
let sdkPromise;
export function loadFacebookSdk(appId) {
if (sdkPromise) return sdkPromise;
sdkPromise = new Promise((resolve, reject) => {
window.fbAsyncInit = () => {
window.FB.init({ appId, cookie: true, xfbml: false, version: 'v26.0' });
resolve(window.FB);
};
const script = document.createElement('script');
script.src = 'https://connect.facebook.net/en_US/sdk.js';
script.async = true;
script.defer = true;
script.crossOrigin = 'anonymous';
script.onerror = () => reject(new Error('Facebook SDK failed to load (blocked?)'));
document.body.appendChild(script);
});
return sdkPromise;
}
Step 3: Add Facebook Login
Facebook Login through the JavaScript SDK only works on HTTPS pages. For local development, serve your site over HTTPS (most dev servers have an option for it, or use a tunnel).
Check whether the visitor is already logged in:
function handleStatus(response) {
if (response.status === 'connected') {
const { accessToken, userID } = response.authResponse;
loadProfile();
} else {
// 'not_authorized' (logged into Facebook, not your app) or 'unknown'
showLoginButton();
}
}
FB.getLoginStatus returns one of three statuses: connected, not_authorized or unknown. When connected, authResponse contains accessToken, expiresIn, signedRequest and userID.
Log in from a click handler (browsers block popups that aren't triggered by a user action):
document.querySelector('#fb-login').addEventListener('click', () => {
FB.login((response) => {
if (response.authResponse) loadProfile();
else console.log('User cancelled login or did not authorize the app.');
}, { scope: 'public_profile,email' });
});
The scope is a comma-separated list of permissions. Users can decline email, and some accounts have no email address, so treat it as optional.
Log out:
FB.logout(() => showLoginButton());
Logging out of your site may also log the person out of Facebook. It does not revoke the permissions they granted.
Step 4: Call the Graph API with FB.api
FB.api sends a Graph API request using the logged-in user's token. Always request the fields you need explicitly:
function loadProfile() {
FB.api('/me', { fields: 'id,name,email,picture' }, (user) => {
if (!user || user.error) {
console.error(user?.error);
return;
}
console.log(user.name, user.email, user.picture?.data?.url);
});
}
Step 5: Verify the token on your server
Never trust a user ID sent from the browser. Send the accessToken to your backend and check it with the debug_token endpoint, using an app access token (APP_ID|APP_SECRET) that exists only on the server:
// Node.js 18+ (built-in fetch)
const appToken = `${process.env.FB_APP_ID}|${process.env.FB_APP_SECRET}`;
const url = new URL('https://graph.facebook.com/debug_token');
url.searchParams.set('input_token', userAccessToken);
url.searchParams.set('access_token', appToken);
const { data } = await (await fetch(url)).json();
if (!data?.is_valid || data.app_id !== process.env.FB_APP_ID) {
throw new Error('Invalid Facebook token');
}
const facebookUserId = data.user_id; // create or look up your user with this
Tokens obtained in the browser are short-lived (Meta describes them as lasting about an hour or two). If your server needs longer access, exchange them for a long-lived token on the server.
Social features: what still works in 2026
Beyond login, the SDK renders Meta's social plugins. Several features older tutorials promise are gone: Meta discontinued the Like button and Comments plugin for third-party websites on February 10, 2026, and the Messenger Chat Plugin stopped working in May 2024, per Meta's social plugins page.
| Feature | Status (October 2026) | Needs Facebook Login? |
|---|---|---|
Share dialog (FB.ui({ method: 'share' })) |
Works | No |
Share button plugin (fb-share-button) |
Works | No |
Page plugin (fb-page) |
Works | No |
Embedded posts and videos (fb-post, fb-video) |
Works, public content only | No |
Like button (fb-like) and Comments plugin (fb-comments) |
Discontinued Feb 10, 2026; render as invisible 0x0 elements | n/a |
| Messenger Chat Plugin | Discontinued May 9, 2024 | n/a |
If your site still has fb-like or fb-comments markup, remove it: it loads Meta's script for nothing and leaves empty space. Meta isn't providing replacements; use a Share button instead of Like, your own or a hosted comment system instead of Comments, and an m.me/yourpage link instead of the chat plugin.
The Share dialog
The Share dialog lets visitors share a URL without your app requesting any permissions or App Review:
document.querySelector('#share').addEventListener('click', () => {
FB.ui({ method: 'share', href: 'https://example.com/article', hashtag: '#webdev' }, () => {});
});
Call it from a click handler so the popup isn't blocked. The callback only receives a response if the person is logged into your app with Facebook Login. Per the Share dialog reference, href defaults to the current page and hashtag is the only optional content parameter.
Facebook builds the preview card from the page's Open Graph tags, so render them on the server for every shareable page (webmaster guide):
<meta property="og:url" content="https://example.com/article" />
<meta property="og:title" content="How we cut our API latency in half" />
<meta property="og:description" content="Profiling, caching and one surprising index." />
<meta property="og:image" content="https://example.com/og/article.png" />
Images are cached by URL, so publish a changed image under a new URL, and use the Sharing Debugger to force a re-scrape of a stale preview.
Page plugin and embedded posts
Plugins are HTML elements (XFBML) that the SDK turns into iframes when you initialize with xfbml: true:
<div class="fb-page"
data-href="https://www.facebook.com/facebook"
data-tabs="timeline,events"
data-width="500"
data-adapt-container-width="true"
data-lazy="true"></div>
<div class="fb-post"
data-href="https://www.facebook.com/YOUR_PAGE/posts/POST_ID"
data-width="500"></div>
The Page plugin accepts widths from 180 to 500 pixels. Embedded posts work only for public posts and accept 350 to 750 pixels. The snippets on Meta's plugin pages still show old version strings such as v3.2; use a current version in FB.init.
In a single-page app the SDK parses the page only once, so after a component that contains a plugin mounts, call:
window.FB?.XFBML.parse(containerElement);
For sharing to any app, not just Facebook, the browser's Web Share API (navigator.share) opens the device's native share sheet without loading third-party JavaScript; fall back to FB.ui where it isn't supported.
Troubleshooting common errors
| Symptom | Likely cause |
|---|---|
FB is not defined |
Your code ran before the SDK loaded; call it inside fbAsyncInit or after the load promise resolves |
| Login dialog says "Can't load URL: the domain of this URL isn't included in the app's domains" | Domain missing from Allowed Domains for the JavaScript SDK |
Login does nothing on http:// |
Login requires HTTPS |
| Only your own account can log in | App is still in Development mode |
email is missing |
User declined it or has no email on the account |
| Script never loads for some users | Ad blocker or browser tracking protection blocked connect.facebook.net |
Limitations and alternatives
- Privacy and consent: loading
sdk.jssends visitor data to Meta. In the EU and UK that generally means loading it only after consent, or only on the pages and clicks that need it. - Blocked script: a meaningful share of visitors block
connect.facebook.net. Always offer another way to sign in, and handle the load error rather than leaving a dead button. - Server-side alternative: Meta also documents a manual login flow that uses redirects instead of the SDK, which avoids loading third-party JavaScript.
- More than one provider: if you need Google, GitHub and email login too, an auth service handles Facebook as one provider among many. Compare options in our auth tools category, see Clerk, or browse free Auth0 alternatives if you want open source and self-hosting.
If your project needs social data without Facebook, our free news and social APIs list covers APIs with free tiers.
FAQ
What is the Facebook SDK used for?
It lets your app use Meta's platform: logging users in with Facebook, sharing content, and reading or writing data through the Graph API. The JavaScript SDK does this for websites; there are separate SDKs for Android, iOS, Unity and servers.
Is the Facebook JavaScript SDK free?
Yes. The SDK and Facebook Login are free to use. You need a Meta developer account and an app; permissions beyond public_profile and email require App Review. The App ID in your front-end code is public; the App Secret must stay on the server.
Which Graph API version should I put in FB.init?
The newest one listed in the Graph API changelog, v26.0 as of October 2026. Versions expire about two years after the next one ships, so record the version you use and upgrade before it expires.
Can I use the Facebook SDK with React or Next.js?
Yes. Load sdk.js once on the client (not during server-side rendering), wait for fbAsyncInit, then call FB methods from event handlers. The promise wrapper above works in any framework.
Did Facebook remove the Like button and comments from websites?
Yes. Meta discontinued the Like button and Comments plugin for external websites on February 10, 2026. Existing embeds don't throw errors; they render as invisible 0x0 elements, so remove the markup. The Share dialog, Share button, Page plugin and embedded posts still work.