
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.
What You’ll Learn in This Guide
- Setting up the Facebook JavaScript SDK
- Authenticating users with Facebook Login
- Making calls to the Graph API to fetch and post data
- Real-world code examples you can use today
- Tackling common issues and best practices
Let’s dive right in!
Why Use the Facebook JavaScript API?
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:
- Super lightweight – minimal impact on page load times
- Asynchronous loading – doesn’t block your other scripts
- Rich functionality – handles authentication, data fetching, and social plugins
- Cross-browser support – works on all modern browsers
- No server-side code needed – perfect for static sites and SPAs
Setting Up the Facebook JavaScript SDK
Step 1: Create a Facebook App
Before writing any code, you need a Facebook App ID. If you don’t have one:
- Go to Facebook Developers
- Click “My Apps” → “Create App”
- Select the app type that best fits your needs (usually “Consumer” or “Business”)
- Fill in the required information
- Once created, find your App ID in the app dashboard
Step 2: Add the SDK to Your Webpage
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.
Authenticating Users with Facebook Login
Authentication is usually the first step when integrating with Facebook. There are two main approaches:
Option 1: Using the Facebook Login Button (Easiest)
<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)
Option 2: Using Your Own Custom Button
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)
Understanding the Login Response
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!
Making Calls to the Facebook Graph API
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.
Basic Structure of an API Call
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)
Example 1: Getting User Profile Info
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)
Example 2: Posting to a User’s Timeline
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)
Example 3: Getting Photos from an Album
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)
Advanced Techniques and Best Practices
Checking Login Status Before Making API Calls
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)
Handling Permissions and Scope
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 manage
Remember that many permissions now require Facebook review before they can be used in production apps!
Handling Errors Gracefully
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)
Implementing Logout Functionality
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)
Troubleshooting Common Issues
“SDK Not Defined” Errors
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)
API Version Mismatches
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.
CORS and Domain Issues
Facebook restricts which domains can use your App ID. If you’re getting unexpected errors:
- Go to your App Dashboard
- Navigate to Facebook Login → Settings
- Add your domains to “Valid OAuth Redirect URIs”
- Enable “Login with the JavaScript SDK”
- Add your domain to “Allowed Domains for the JavaScript SDK”
Mobile Browser Quirks
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)
Complete Working Example
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)
Final Thoughts: What Makes the Facebook JavaScript SDK So Valuable
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:
- Simplicity – Basic integration takes just minutes
- Performance – Minimal impact on page load times
- Flexibility – Works with any frontend stack or framework
- Power – Access to Facebook’s vast ecosystem of data and features
As Facebook continues to evolve its platform, the JavaScript SDK remains the fastest way to tap into their ecosystem from your frontend applications.
Resources to Keep You Updated
Facebook’s API changes regularly, so stay up to date with these resources:
- Official Facebook JavaScript SDK Documentation
- Graph API Explorer – Interactive tool to test API calls
- Changelog – Keep track of API changes
I hope this guide helps you get started with the Facebook JavaScript API. Happy coding!
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
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
😀 thnks for the info 😉 🙁 8) (^^^) :putnam: :42: 😛
i got this in popup dialog : An error occurred. Please try again later.
Awesome easy tutorial! 🙂 thanks a lot! better than facebook’s tutorial 😀
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.
Hello Sir, I want to add button of add photos on my web application like facebook
And then I want to share selected image on facebook wall.
Please give me code or Any Idea. My EmailID is [email protected].
Thanks
Thank you sir, finally a post that makes sense. Facebook API docs are the stupidest and most unorganized thing i’ve ever seen. Thanks for these instructions!
Hello Ali Ahsan i really liked your post!
But when i pasted the code of updating the status from your website, it gave me the error “Couldn’t Publish Data” which might be because of response error. Can you tell me why am i getting the error?
Hello sir,
I’m trying to post an image on facebook page with different login not as a admin of the page. But i’m getting authorization issue. How can i achieve that using javascript API code. Please help kindly.
after clearing history in firefox …im getting error “Not Logged In: You are not logged in. Please login and try again” when i try to login with facebook …can anybody help me ??
Hi There!
I’m glad to finally find some example on Facebook’s Javascript SDK coding, I’m tryng to control an facebook video player embeeded on my website with no success, i just want to apply the “.pause()” method to stop the player sound from an external button (this button also hides the player and unhide another one via CSS, using jquery addClass / removeClass.
Thank you in advance for your help.
Thanks BRO! I’m found this article on 15 page in gnoogle. You must be FIRST!
fb v13 , don’t have publish stream , it post to page, but not to timeline, what is solution ?