NextJS Facebook SDK - FB.login not working

836 Views Asked by At

I have a NextJS 13 project I am trying to add social login to.

I just can't seem to get FB.login to respond.

All of the examples I can find are for JavaScript or React, not NextJS which may do things a little differently.

My code:

    import Script from 'next/script';

    const LoginPage = () => {


        const facebookLoginButton = async (event) => {

            console.log("Facebook button!")

            setLoading(true);

            window.fbAsyncInit = function() {
                FB.init({
                    appId      : MY_FACEBOOK_APP_ID,
                    status     : true, 
                    cookie     : true,
                    xfbml      : true,
                    version    : 'v16.0'
                });
            };

            const { authResponse } = await new Promise(() => {window.FB.login}); <---Hangs here

            console.log(`login.js - Facebook Auth response was: `, authResponse)

        }

        return(

                <div>
                    <p>Login With:</p>
                    <Image src="facebooklogin-button.png" width="300" height="46" onClick={facebookLoginButton} alt="Login"></Image>
                </div>
                
                <Script src="https://connect.facebook.net/en_US/sdk.js" strategy="beforeInteractive"></Script>
            
        )

    }
    export default LoginPage;

Notice I am using the NextJS script tag to load the Facebook SDK, I have also tried this method but same result:

import { useEffect } from 'react'
    
     useEffect(() => {
        window.fbAsyncInit = function() {
          window.FB.init({
            appId            : 'MY_FACEBOOK_APP_ID',
            autoLogAppEvents : true,
            xfbml            : true,
            version          : 'v16.0'
          });
        };
     
        (function(d, s, id) {
          let 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'));
      }, []);
      }

How can I get a response from FB.login ? I need to get the accessToken to pass to my back end.

I have thought about using the npm package "react-facebook-login" but it was last updated 5 years ago so I'd rather stay away. I also see that Next-Auth has a faceboook social login, but I don't think that can provide the accessToken, it just does everything for you.

Any help appreciated!

0

There are 0 best solutions below