How to Integrate Facebook Login on the Web – A Step‑by‑Step Guide
Learn how to set up Facebook Login for your website, from initializing the JavaScript SDK to handling OAuth tokens and avoiding common pitfalls.
03 Apr 2026, 05:43 UTC

What You Need to Know First
Facebook Login is an OAuth 2.0 flow that exchanges a user’s credentials for an access token. The token is short‑lived (≈ 1–2 h) unless you perform a server‑side exchange. The JavaScript SDK is the most common client‑side entry point, but you must keep the App Secret on the server and serve all pages over HTTPS. The following steps assume you already have a Facebook App on the Developer Dashboard and that you have enabled Client OAuth Login and Web OAuth Login in the settings.
Step 1: Prepare Your Facebook App
- In the App Dashboard, go to Settings > Basic and note the App ID and App Secret. The secret must never appear in client code.
- Navigate to Facebook Login > Settings and add the exact URL of the page that will receive the OAuth redirect (e.g.
https://example.com/auth/facebook/callback) to Valid OAuth Redirect URIs. A mismatch will cause the login dialog to fail. - Enable Client OAuth Login and Web OAuth Login under Facebook Login > Settings if they are not already checked.
Step 2: Add the JavaScript SDK
Insert the SDK script tag in the <head> of your page. The script loads asynchronously and sets a global FB object once ready.
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
Step 3: Initialize the SDK
Call FB.init after the SDK is loaded. Use a hard‑coded API version (e.g. v17.0) to prevent breaking changes when Facebook releases a new SDK.
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
cookie : true, // Enable cookies to allow server‑side session access
xfbml : true, // Parse social plugins on the page
version : 'v17.0' // Pin to a specific API version
});
};
Step 4: Trigger the Login Flow
Use FB.login when the user clicks a “Login with Facebook” button. Specify the scopes you require. The scope string is comma‑separated; for example, email,public_profile.
function loginWithFacebook() {
FB.login(function(response) {
handleLoginResponse(response);
}, {scope: 'email,public_profile'});
}
Step 5: Handle the Callback
The callback receives a response object. A successful login contains response.authResponse with an accessToken, expiresIn, and signedRequest. If the user cancels or the login fails, response.status will be not_authorized or unknown.
function handleLoginResponse(response) {
if (response.status === 'connected') {
// User logged in and authorized the app
const accessToken = response.authResponse.accessToken;
// Store or send this token to your server for validation
fetchUserProfile(accessToken);
} else if (response.status === 'not_authorized') {
alert('You need to authorize the app.');
} else {
alert('Login failed or was cancelled.');
}
}
Step 6: Retrieve User Data
Once you have an access token, call FB.api to fetch the user’s profile. The fields parameter limits the returned data to what you requested in the scope.
function fetchUserProfile(token) {
FB.api('/me', {fields: 'name,email', access_token: token}, function(profile) {
console.log('User profile:', profile);
// Send profile to your backend or render it on the page
});
}
Step 7: Manage Tokens
- Short‑lived tokens expire after ~1–2 hours. Use
FB.getLoginStatusto refresh automatically if the user is still on the page. - For persistence, exchange the short‑lived token for a long‑lived one on your server: send a POST to
https://graph.facebook.com/v17.0/oauth/access_tokenwithgrant_type=fb_exchange_token, yourclient_id,client_secret, and the short‑livedfb_exchange_token. The response contains a token that lasts ~60 days. - Never expose the App Secret in client code. All token exchanges that involve the secret must run server‑side.
- Validate the token signature and expiration on the server using the Token Debugger API or by inspecting the
expclaim when the token is a JWT.
Common Pitfalls & How to Avoid Them
- Missing or malformed redirect URI: The URI in the callback must match exactly what you entered in the Dashboard, including protocol and trailing slash.
- Running on HTTP: Facebook rejects login requests from non‑HTTPS origins in production. Use a valid SSL certificate.
- Incorrect SDK version: Omitting the
versionfield defaults to the latest API, which may change required parameters. Pin to a known stable version. - Exposing the App Secret: Even a single leak can allow attackers to impersonate your app. Store it in environment variables on the server.
- Ignoring error states: If the callback’s
statusis notconnected, display a clear message. Do not assume success. - Using the access token without checking
expires_inor signature can lead to silent failures when the token becomes invalid.
Testing & Verification
- Open the page in a browser over HTTPS.
- Open the console and click the login button. Verify that a network request to
https://graph.facebook.com/v17.0/oauth/access_tokenappears. - Check that
FB.getLoginStatusreturnsconnectedand that theaccessTokenis present. - Use the Graph API Explorer with the obtained token to query
/me. The returned fields should match your requested scopes. - Temporarily remove a required scope (e.g.,
email) from theFB.logincall and observe the error response in the console.
Summary
Integrating Facebook Login involves: setting up a Facebook App with the correct redirect URI, loading the JavaScript SDK, initializing it with a pinned API version, triggering the OAuth dialog, handling the callback, fetching user data, and managing short‑lived tokens. Keep the App Secret server‑side, serve over HTTPS, and always validate the access token. By following the steps above and avoiding the common pitfalls, you can add a reliable social login to your web application.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.