\n```\n2️⃣ Initialize it in a component (e.g., App.js) after the script loads:\n```js\nwindow.fbAsyncInit = function() {\n FB.init({\n appId : '',\n cookie : true,\n xfbml : true,\n version : 'v17.0'\n });\n};\n```\n3️⃣ Use `FB.login` or `FB.getLoginStatus` in your UI handlers to trigger the login flow. The SDK works in any React version ≥7.0.\n[Source: Facebook for Developers]"}},{"@type":"Question","name":"Can I use Firebase Authentication with Facebook instead of the raw SDK?","acceptedAnswer":{"@type":"Answer","text":"Yes. Enable the Facebook provider in the Firebase console, add your Facebook App ID and Secret, then install the Firebase SDK:\n```bash\nnpm install firebase\n```\nIn your React code:\n```js\nimport { getAuth, signInWithPopup, FacebookAuthProvider } from 'firebase/auth';\nconst provider = new FacebookAuthProvider();\nsignInWithPopup(getAuth(), provider)\n .then(result => {\n const user = result.user; // Facebook‑authenticated user\n })\n .catch(error => console.error(error));\n```\nFirebase handles token exchange and session management, simplifying the integration.\n[Source: Firebase Docs]"}},{"@type":"Question","name":"What steps are required to configure OAuth redirect URIs for Facebook Login in a React app?","acceptedAnswer":{"@type":"Answer","text":"1️⃣ Open your app in the Facebook Developer Dashboard → Settings → Basic.\n2️⃣ Add your domain under **App Domains**.\n3️⃣ Click **Add Platform → Website** and set **Site URL** to `https://your-domain.com` (or `http://localhost:3000` for development).\n4️⃣ Go to **Facebook Login → Settings** and list the exact redirect URIs, e.g., `https://your-domain.com/auth/callback`.\n5️⃣ Save changes and use the same URI in your React routing (e.g., a `/auth/callback` component) to capture the access token.\n[Source: Facebook Login Docs]"}},{"@type":"Question","name":"How can I troubleshoot the \"Invalid OAuth redirect URI\" error when using Facebook Login?","acceptedAnswer":{"@type":"Answer","text":"The error means the redirect URI sent by your app doesn't match any URI saved in the Facebook Dashboard. Verify that:\n- The protocol (`http` vs `https`), domain, port, and path are identical.\n- The URI is listed under **Facebook Login → Settings → Valid OAuth Redirect URIs**.\n- No trailing slashes or query strings differ.\nAfter correcting the URI, clear browser cookies and retry the login flow.\n[Source: Facebook Developer Support]"}}]}]}

Archilo: helping architecture work become visible.

Explore the ecosystem →

Updates & announcements

Archilo: helping architecture work become visible.
Archilo: helping architecture work become visible.

A focused platform for architecture portfolios, research, talent and creative opportunity. Built for architects, students and studios.

Enally announcement
Enally: building useful things, together.

A founder-led ecosystem connecting products, services, knowledge, community and opportunities. One belief, expressed in different ways.

Enally announcement
Build with us: internships, contributors and partnerships.

Practical ways for young builders, contributors and domain experts to learn through real products and useful responsibility.

Archilo growing steadily
Archilo growing steadily

Architecture portfolios and research pages now serve 5,000+ creative professionals.

Humble campus expansion
Humble campus expansion

Verified student communities now active across multiple campuses with 2K+ members.

Faaho partner beta live
Faaho partner beta live

Zero-brokerage living discovery is now available in partner beta. Technology by Enally.

Enally announcement
Enally Labs launched

Applied AI experiments, internal agents and prototype products now live under Labs.

Enally announcement
Blog redesigned

The Enally blog now brings practical guides, opportunities and ecosystem knowledge together.

Enally announcement
Services: SEO to AIO

Five-layer visibility services now available — SEO, AEO, GEO, SXO and AI Optimization.

Enally announcement
Build with us program

Internships, campus ambassadors and contributor roles open for builders who want real ownership.

Enally announcement
Company website rebuilt

Enally.in redesigned with improved performance, accessibility and dark theme support.

Tech

How to integrate Facebook Login API into your React or Other App v7.0 and Above

Guidance on implementing Facebook Login API into various applications, such as React or others. It outlines three distinct methods: utilizing the SDK, integrating with Firebase Auth using Facebook authentication provider, and setting up Facebook Manual login.

How to integrate Facebook Login API into your React or Other App v7.0 and Above
What you'll learn

Guidance on implementing Facebook Login API into various applications, such as React or others. It outlines three distinct methods: utilizing the SDK, integrating with Firebase Auth using Facebook authentication provider, and setting up Facebook Manual login.

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

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. Go to the App review menu on Facebook Developer Dashboard, then navigate to Permissions and features.
  2. Click on "Get advanced access for the public_profile permission."
  3. Confirm Advanced Access for public_profile.
  4. 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.

Frequently asked questions

1️⃣ Create a Facebook app in the Facebook Developer Console. 2️⃣ Add your React site URL as a valid OAuth redirect URI. 3️⃣ Install the Facebook SDK (`npm i facebook-sdk`) or Firebase (`npm i firebase`) in your project. 4️⃣ Initialize the SDK with your App ID in a component (e.g., `useEffect`). 5️⃣ Call `FB.login` (SDK) or `signInWithPopup` (Firebase) to trigger the login flow. 6️⃣ Handle the response to obtain the access token and user profile, then store it securely (e.g., in context or Redux).

In the Facebook Developer Dashboard, go to **Settings > Basic** and set the **App Domains** to your domain (e.g., `example.com`). Under **Settings > Advanced**, add your **Site URL** and **OAuth Redirect URIs** (e.g., `https://example.com/auth/facebook/callback`). Ensure **Login with the JavaScript SDK** is enabled and the **Valid OAuth Redirect URIs** match the route in your React app that processes the token.

• **Facebook SDK** – Direct integration with Facebook; you manage the access token, permissions, and API calls yourself. Ideal for custom permission handling and when you need only Facebook login. • **Firebase Authentication** – Wrapper around the Facebook SDK; Firebase handles token exchange, session persistence, and provides a unified API for multiple providers. Easier to implement and works well if you already use Firebase services.

After a successful login, use the returned access token to call the Graph API: `FB.api('/me', { fields: 'id,name,email,picture' }, response => { /* handle user data */ });` or, with Firebase, `getAdditionalUserInfo(result).profile` after `signInWithPopup`. The response includes the user's Facebook ID, name, email (if permission granted), and profile picture URL.

You need a Facebook Developer account, a Facebook app (created in both normal and business mode), and a React project set up with npm or yarn. Also ensure the app’s domain, site URL, and OAuth redirect URIs are configured in the Facebook Developer Dashboard.

1️⃣ Include the SDK script in public/index.html inside the `<head>` tag: ```html <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script> ``` 2️⃣ Initialize it in a component (e.g., App.js) after the script loads: ```js window.fbAsyncInit = function() { FB.init({ appId : '<YOUR_APP_ID>', cookie : true, xfbml : true, version : 'v17.0' }); }; ``` 3️⃣ Use `FB.login` or `FB.getLoginStatus` in your UI handlers to trigger the login flow. The SDK works in any React version ≥7.0. [Source: Facebook for Developers]

Yes. Enable the Facebook provider in the Firebase console, add your Facebook App ID and Secret, then install the Firebase SDK: ```bash npm install firebase ``` In your React code: ```js import { getAuth, signInWithPopup, FacebookAuthProvider } from 'firebase/auth'; const provider = new FacebookAuthProvider(); signInWithPopup(getAuth(), provider) .then(result => { const user = result.user; // Facebook‑authenticated user }) .catch(error => console.error(error)); ``` Firebase handles token exchange and session management, simplifying the integration. [Source: Firebase Docs]

1️⃣ Open your app in the Facebook Developer Dashboard → Settings → Basic. 2️⃣ Add your domain under **App Domains**. 3️⃣ Click **Add Platform → Website** and set **Site URL** to `https://your-domain.com` (or `http://localhost:3000` for development). 4️⃣ Go to **Facebook Login → Settings** and list the exact redirect URIs, e.g., `https://your-domain.com/auth/callback`. 5️⃣ Save changes and use the same URI in your React routing (e.g., a `/auth/callback` component) to capture the access token. [Source: Facebook Login Docs]

The error means the redirect URI sent by your app doesn't match any URI saved in the Facebook Dashboard. Verify that: - The protocol (`http` vs `https`), domain, port, and path are identical. - The URI is listed under **Facebook Login → Settings → Valid OAuth Redirect URIs**. - No trailing slashes or query strings differ. After correcting the URI, clear browser cookies and retry the login flow. [Source: Facebook Developer Support]

Keep learning

Related articles