Introduction
In today's interconnected world, providing users with the convenience of social media login options can significantly enhance the user experience of your application. Facebook Login API offers a seamless way for users to sign in to your app using their Facebook credentials. In this guide, we'll explore three different approaches to integrating Facebook Login API into a React app. We'll cover using the SDK, leveraging Firebase Authentication with Facebook, and setting up manual login steps.
Prerequisites
Before we dive into the implementation, ensure you have the following:
-
Facebook Developer Account: You need to have a Facebook Developer account to create and manage your Facebook apps. Facebook for Developers
-
Facebook App: Create a Facebook app in both normal and business mode. This allows you to access different features based on your app's requirements.
Setting Up Facebook Authentication
-
Create a Facebook App:
- Log in to your Facebook Developer account and navigate to the Developer Dashboard.
- Click on "Create App" and follow the prompts to create your app.
- Configure your app settings, including the platform (web), basic information, and contact email.
-
Configure Auth URL and Callbacks:
- In the Facebook Developer Dashboard, go to your app settings.
- Under "Settings" > "Basic," configure the "App Domains," "Site URL," and "Privacy Policy URL" fields.
- Add platform-specific OAuth redirect URIs for your React app.
-
Retrieve App Credentials:
- Once your app is created, note down the App ID and App Secret. You'll need these credentials to integrate Facebook Login into your React app.
-
Enable Facebook Login:
- In your Facebook Developer Dashboard, navigate to "Products" > "Facebook Login."
- Enable Facebook Login and configure settings such as OAuth redirect URIs and permissions. Facebook Login Documentation
Implementation
Now let's dive into the code implementation for each approach:
Using SDK:
javascript
// LoginWithFB.js
import React, { useContext } from 'react';
import FacebookLogin from 'react-facebook-login';
import { LoginAuthContext } from '../Auth/loginAuthContext';
const LoginWithFB = () => {
const { setAccessToken, setUserID } = useContext(LoginAuthContext);
const responseFacebook = async (response) => {
try {
await setAccessToken(response.accessToken);
await setUserID(response.userID);
console.log(response);
if (response.status !== 'unknown') {
alert('Login Successful');
} else {
alert('Login Failed');
}
} catch (error) {
console.error('Error:', error);
alert('Login Failed');
}
}
return (
<div>
<FacebookLogin
appId="XXXXXXXXXXXXXXXX"
autoLoad={false}
fields="name,picture"
callback={responseFacebook}
/>
</div>
);
};
export default LoginWithFB;
Firebase Authentication with Facebook:
1. Enable Facebook Auth Provider
2. Add these:

3. Add oAuth uri and others

javascript
// LoginWithFB.js firebase
import React, { useContext, useState } from 'react';
import FacebookLogin from 'react-facebook-login';
import { LoginAuthContext } from '../Auth/loginAuthContext';
import { FacebookAuthProvider, signInWithPopup } from "firebase/auth";
import { auth } from '../../firebase';
const LoginWithFB = () => {
const { setAccessToken, setUserID } = useContext(LoginAuthContext);
const provider = new FacebookAuthProvider();
const [userData, setUserData] = useState({});
const handleFacebookLogin = (response) => {
signInWithPopup(auth, provider).then((result) => {
const credential = FacebookAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
setAccessToken(accessToken);
setUserID(result.user.uid);
setUserData(response);
console.log('response', response);
alert('Login successful');
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = FacebookAuthProvider.credentialFromError(error);
console.log(errorCode, errorMessage, email, credential);
});
}
return (
<div>
<button className="btn" onClick={handleFacebookLogin}>Login with Facebook</button>
</div>
);
};
export default LoginWithFB;
// firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export { auth };
Manual Login Setup:
javascript
// LoginWithFB.js
import React, { useEffect } from 'react';
const LoginWithFB = () => {
useEffect(() => {
window.fbAsyncInit = function() {
FB.init({
appId: 'YOUR_APP_ID',
cookie: true,
xfbml: true,
version: 'v8.0'
});
FB.AppEvents.logPageView();
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the Facebook 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'));
}, []);
const statusChangeCallback = (response) => {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
console.log('loggedin');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
} else {
document.getElementById('status').innerHTML = '';
}
};
const handleFacebookLogin = () => {
FB.login(function(response) {
statusChangeCallback(response);
});
};
return (
<>
<button onClick={handleFacebookLogin}>Login with Facebook</button>
<div id="status"></div>
</>
);
};
export default LoginWithFB;
Packages required for different methods:
- Using SDK:
npm install react-facebook-login
- Firebase Authentication with Facebook:
npm install firebase
Advanced Access for Facebook Login for Business
To use Facebook Login for Business and access advanced features, follow these steps:
- Go to the App review menu on Facebook Developer Dashboard, then navigate to Permissions and features.
- Click on "Get advanced access for the public_profile permission."
- Confirm Advanced Access for public_profile.
- Check the box agreeing to use any data received through public_profile in accordance with allowed usage.
Conclusion
Integrating Facebook Login API into your React app offers a convenient way for users to sign in and engage with your application. By following the steps outlined in this guide, you can seamlessly implement Facebook authentication using different approaches, catering to your app's specific requirements. Whether you choose to use the SDK, Firebase Authentication, or set up manual login steps, providing users with the option to sign in with Facebook can enhance user experience and streamline the authentication process.
Comment
Coming Soon