Search code examples
facebookreactjsfacebook-javascript-sdkcreate-react-app

Facebook is not initialized when using Facebook Login with React in Production


I love React, it has quickly become my favorite development tool. It is a fantastic library that creates the kind of flexibility I've always dreamed about.

That said, I'm having a very hard time getting Facebook login to work with React in production.

I have tried all of the following methods. In all three cases, I implemented the examples exactly as shown in the code using the simplest possible technique:

Everything works great in development. :)

When I create the production build using create-react-app and push it live, it breaks and reports: Error: Facebook is not initialized or Uncaught TypeError: Cannot read property 'login' of undefined where undefined is FB.

Basically it seems like the Facebook javascript SDK is not loaded or initialized.

The first two links above are for existing component libraries, but the third is a custom implementation that places the Facebook initialization code in the index.html file and creates an event listener. The results are the same in all three examples.

It is as if something about the create-react-app compression method is obfuscating the variables to the point that Facebook can no longer work, or at least is not available to the react code. This includes all calls to window.FB as recommended in many tutorials.

I've been working at this for a couple of weeks now (off and on) and am now turning to the hive mind. Anyone have any ideas on how to get Facebook to actually work with Facebook's own code library (React)? It seems so painfully odd that it causes this much trouble and I have been unable to find a clear solution that works in production.


Solution

  • Most of the debugging steps are already mentioned in the comments section.

    Here are the steps laid down: 1) Check the network tab in your browser's console and see if the request to load FB's SDK is successful or not

    2) Most common culprit is some extension like Ad-Blocker blocking such async requests which loads JS on your web page. Disable it or try it incognito mode

    3) Other common mistake I have seen is forgetting to use the FB.init({ // config }); function - which is the actual call which initializes the fb sdk and makes available the FB variable globally.