I’ve spent countless hours wrestling with the Facebook JavaScript API, and I’m here to share everything I’ve learned. Whether you’re completely new to it or just looking to refresh your knowledge, this guide will get you up and running in no time.
Let’s dive right in!
The Facebook JavaScript SDK is probably the most powerful yet straightforward way to integrate with Facebook’s platform from your frontend. Here’s why you should consider it:
Before writing any code, you need a Facebook App ID. If you don’t have one:
The basic setup is surprisingly simple. Just add this snippet right after your opening <body> tag:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // Replace with your App ID
cookie : true, // Enable cookies for server-side authentication
xfbml : true, // Parse social plugins on the page
version : 'v22.0' // Use latest API version (as of May 2025)
});
};
</script>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>Code language: HTML, XML (xml) That’s it! The SDK will load asynchronously, and you’re ready to start using it.
Authentication is usually the first step when integrating with Facebook. There are two main approaches:
<fb:login-button
scope="public_profile,email"
onlogin="checkLoginStatus();">
</fb:login-button>
<script>
function checkLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// User is logged in and has authorized your app
console.log('Logged in successfully!');
console.log('Access token:', response.authResponse.accessToken);
console.log('User ID:', response.authResponse.userID);
} else {
// User either isn't logged in or hasn't authorized your app
console.log('Not fully logged in.');
}
});
}
</script>Code language: HTML, XML (xml) Sometimes you want your own styled button. Here’s how:
<button id="fbLogin">Login with Facebook</button>
<script>
document.getElementById('fbLogin').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
// User authorized your app
console.log('Welcome! Getting your info...');
FB.api('/me', { fields: 'name,email' }, function(response) {
console.log('Good to see you, ' + response.name + '!');
console.log('Email: ' + response.email);
});
} else {
console.log('User cancelled login or didn\'t authorize the app.');
}
}, { scope: 'public_profile,email' }); // Permissions requested
});
</script>Code language: HTML, XML (xml) When someone logs in, Facebook returns an authResponse object with these key properties:
accessToken: The token you’ll use for API callsuserID: The Facebook ID of the logged-in userexpiresIn: When the token expires (in seconds)Keep that accessToken safely managed – you’ll need it for API calls!
The Graph API is Facebook’s primary way to get data in and out of their platform. With the JavaScript SDK, calling it is a breeze.
FB.api(
'/endpoint', // The API path you want to access
'http-method', // GET, POST, DELETE (defaults to GET)
{parameters}, // Optional parameters to send
function(response) { // Callback function
// Handle the response
}
);Code language: PHP (php) FB.api('/me', { fields: 'name,email,picture' }, function(response) {
if (!response || response.error) {
console.error('Error fetching user data:', response.error);
return;
}
// Do something with the data
console.log('User Info:', response);
document.getElementById('userName').textContent = response.name;
document.getElementById('userEmail').textContent = response.email;
document.getElementById('userPic').src = response.picture.data.url;
});Code language: JavaScript (javascript) function postToTimeline() {
var content = document.getElementById('postContent').value;
FB.api('/me/feed', 'post', { message: content }, function(response) {
if (!response || response.error) {
console.error('Error posting to timeline:', response.error);
alert('Sorry, could not post to your timeline. ' + response.error.message);
return;
}
alert('Posted successfully! Post ID: ' + response.id);
});
}Code language: JavaScript (javascript) FB.api('/me/photos', { fields: 'images,name,created_time', limit: 10 }, function(response) {
if (!response || response.error) {
console.error('Error fetching photos:', response.error);
return;
}
var photoContainer = document.getElementById('photos');
response.data.forEach(function(photo) {
var img = document.createElement('img');
<em>// Use the smallest suitable image from the array of sizes</em>
img.src = photo.images[photo.images.length - 1].source;
img.alt = photo.name || 'Facebook photo';
photoContainer.appendChild(img);
});
});Code language: JavaScript (javascript) Always check if a user is already logged in when your page loads:
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
cookie : true,
xfbml : true,
version : 'v22.0'
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// Already logged in, you can make API calls immediately
loadUserData();
} else {
// Show login button or prompt
document.getElementById('loginPrompt').style.display = 'block';
}
});
};
function loadUserData() {
// Your API calls here
}Code language: JavaScript (javascript) Different API endpoints require different permissions. When you request login, specify all the permissions you need:
FB.login(function(response) {
// Handle login response
}, {
scope: 'public_profile,email,user_posts,user_photos,publish_to_groups'
});Code language: JavaScript (javascript) Important permissions to know:
public_profile: Basic profile info (always included)email: User’s email addressuser_posts: Access to posts on their timelineuser_photos: Access to their photospublish_to_groups: Ability to post to groups they manageRemember that many permissions now require Facebook review before they can be used in production apps!
The Graph API can return errors for many reasons. Always handle them:
FB.api('/me/feed', function(response) {
if (!response) {
console.error('No response from Facebook');
showErrorMessage('Network error. Please check your connection and try again.');
return;
}
if (response.error) {
console.error('API Error:', response.error);
if (response.error.code === 190) {
// Invalid or expired token
showErrorMessage('Your session has expired. Please log in again.');
promptRelogin();
} else if (response.error.code === 100) {
// Permission issue
showErrorMessage('You need to grant additional permissions for this feature.');
promptPermissions();
} else {
// Generic error
showErrorMessage('Something went wrong: ' + response.error.message);
}
return;
}
// Success! Process response
processData(response);
});Code language: JavaScript (javascript) Don’t forget to let users log out:
function logoutFromFacebook() {
FB.logout(function(response) {
console.log('User logged out');
// Update your UI to reflect logged-out state
document.getElementById('loggedInContent').style.display = 'none';
document.getElementById('loginPrompt').style.display = 'block';
});
}Code language: JavaScript (javascript) If you get errors saying FB is not defined, your code might be executing before the SDK is loaded. Always wrap your FB calls in the fbAsyncInit function or make sure they run after the SDK is loaded:
// Bad - might execute before FB is defined
documentReady(function() {
FB.getLoginStatus(); // Error if SDK isn't loaded yet!
});
// Good - wait for FB to be initialized
window.fbAsyncInit = function() {
FB.init({/*...*/});
// Now it's safe to use FB
FB.getLoginStatus();
};Code language: JavaScript (javascript) Facebook regularly updates its API, deprecating old endpoints and changing behaviors. If something that used to work suddenly breaks, check for API version changes.
Always specify the API version explicitly in your initialization:
FB.init({
appId: 'YOUR_APP_ID',
version: 'v22.0' // Be explicit about which version you're using
});Code language: JavaScript (javascript) As of May 2025, I recommend using v22.0, which is the latest stable version.
Facebook restricts which domains can use your App ID. If you’re getting unexpected errors:
The login popup can behave differently on mobile browsers. Test thoroughly and consider using the full redirect login flow for mobile rather than popups:
// Detect if we're on mobile
if (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
// Use redirect flow for mobile
FB.login(null, {redirect_uri: 'https://your-redirect-url.com/callback'});
} else {
// Use popup for desktop
FB.login(function(response) {
// Handle response
});
}Code language: JavaScript (javascript) Here’s a complete, working example that puts everything together:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook JavaScript API Demo</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
#userData { display: none; margin-top: 20px; }
#loginPrompt { margin: 20px 0; }
.profile-pic { width: 100px; height: 100px; border-radius: 50%; }
button { padding: 10px 15px; background: #1877F2; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #166FE5; }
textarea { width: 100%; height: 100px; margin: 10px 0; }
</style>
</head>
<body>
<h1>Facebook JavaScript API Demo</h1>
<div id="loginPrompt">
<p>Please log in to see your Facebook data:</p>
<button id="fbLoginBtn">Login with Facebook</button>
</div>
<div id="userData">
<img id="userPic" class="profile-pic" src="" alt="Profile picture">
<h2 id="userName"></h2>
<p>Email: <span id="userEmail"></span></p>
<div id="postForm">
<h3>Post to your timeline</h3>
<textarea id="postContent" placeholder="What's on your mind?"></textarea>
<button id="postBtn">Post to Facebook</button>
</div>
<button id="logoutBtn">Logout</button>
<div id="userPhotos">
<h3>Your recent photos</h3>
<div id="photos"></div>
</div>
</div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', <em>// Replace with your App ID</em>
cookie : true,
xfbml : true,
version : 'v22.0'
});
checkLoginState();
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function checkLoginState() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
document.getElementById('loginPrompt').style.display = 'none';
document.getElementById('userData').style.display = 'block';
loadUserData();
loadUserPhotos();
} else {
document.getElementById('loginPrompt').style.display = 'block';
document.getElementById('userData').style.display = 'none';
}
});
}
function loadUserData() {
FB.api('/me', { fields: 'name,email,picture.width(100).height(100)' }, function(response) {
if (!response || response.error) {
console.error('Error loading user data');
return;
}
document.getElementById('userName').textContent = response.name;
document.getElementById('userEmail').textContent = response.email || 'Not available';
document.getElementById('userPic').src = response.picture.data.url;
});
}
function loadUserPhotos() {
FB.api('/me/photos', { fields: 'images,name', limit: 5 }, function(response) {
if (!response || response.error) {
console.error('Error loading photos:', response.error);
return;
}
var photoContainer = document.getElementById('photos');
photoContainer.innerHTML = '';
if (response.data.length === 0) {
photoContainer.innerHTML = '<p>No photos found</p>';
return;
}
response.data.forEach(function(photo) {
var img = document.createElement('img');
// Use the smallest suitable image
img.src = photo.images[photo.images.length - 1].source;
img.alt = photo.name || 'Facebook photo';
img.style.width = '150px';
img.style.margin = '5px';
photoContainer.appendChild(img);
});
});
}
document.getElementById('fbLoginBtn').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
checkLoginState();
} else {
console.log('Login cancelled or failed');
}
}, { scope: 'public_profile,email,user_posts,user_photos' });
});
document.getElementById('postBtn').addEventListener('click', function() {
var content = document.getElementById('postContent').value;
if (!content.trim()) {
alert('Please enter something to post');
return;
}
FB.api('/me/feed', 'post', { message: content }, function(response) {
if (!response || response.error) {
console.error('Error posting to timeline:', response.error);
alert('Sorry, could not post to your timeline: ' +
(response.error ? response.error.message : 'Unknown error'));
return;
}
alert('Posted successfully!');
document.getElementById('postContent').value = '';
});
});
document.getElementById('logoutBtn').addEventListener('click', function() {
FB.logout(function(response) {
checkLoginState();
});
});
</script>
</body>
</html>Code language: HTML, XML (xml) After years of working with various social media APIs, I still find the Facebook JavaScript SDK to be one of the most developer-friendly. The asynchronous loading, robust error handling, and comprehensive feature set make it perfect for frontend developers who want to integrate social features without diving into complex server-side code.
The key advantages that make it stand out:
As Facebook continues to evolve its platform, the JavaScript SDK remains the fastest way to tap into their ecosystem from your frontend applications.
Facebook’s API changes regularly, so stay up to date with these resources:
I hope this guide helps you get started with the Facebook JavaScript API. Happy coding!
Learn python file handling from scratch! This comprehensive guide walks you through reading, writing, and managing files in Python with real-world examples, troubleshooting tips, and…
You've conquered the service worker lifecycle, mastered caching strategies, and explored advanced features. Now it's time to lock down your implementation with battle-tested service worker…
Unlock the full potential of service workers with advanced features like push notifications, background sync, and performance optimization techniques that transform your web app into…
This website uses cookies.
View Comments
Hi,
Thank you very much to post this. It helped me a lot to complete my application.
Thanks a lot.
Good article. Thanks for putting this information. Great help ;-Q
:D thnks for the info ;) :( 8) (^^^) :putnam: :42: :P
i got this in popup dialog : An error occurred. Please try again later.
Awesome easy tutorial! :-) thanks a lot! better than facebook's tutorial :-D
It' s definitely much better then the facebook's one. Nice work. Clear and easy to follow tutorial.
Thanks a lot before, how can i add some permission to access more information from users in that js code???
Great post. Here is a blog post I recently wrote that explains how to actually log a user into your site using "Login with Facebook." I was surprised that I couldn't find a great example of how to complete the process.
Basically, the Facebook Javascript API returns an access token to your client-side code. You can then submit that token to the server, use it to fetch the user's Facebook UserID using the Social Graph API, which you can use as the unique ID for all users in your system (who are using Facebook credentials for login).
https://www.modernsignal.com/overview_of_login_with_facebook
I searched everywhere for three days, I am glad you provided a clear and perfect explanation to this...
Thanks a million!
Nice Tutorial.
Thankyou very much.