Facebook login with React and GraphQL
Many developers use ready-made libs to perform OAuth2 authorization to services like Facebook, Google or Github when the procedure is, in fact, really easy to implement and customize.
You can check out presented features in action on our development-version website.
Yet another time tracking app for freelancers (if it’s not working at the moment try again later)dev.myworktime.online
How Facebook OAuth2 works?
- user clicks a sign-in button and he is redirected to Facebook’s App consent screen
- then the user is redirected back to predefined redirectUrl along with special code from Facebook
- app front-end must send this code to your app’s back-end
- back-end uses this code to get Facebook User information
Register Facebook App
First, go to Facebook Developer console and set up new App. You may use production name — developer version will be added as a test-app below production one.
After app is created you have to add Facebook Login product to enable login from Facebook feature for you website.
In a wizard that will show up you should provide production URL for your website. If you don’t have one use google.com — it doesn’t matter at this stage.
To enable developer version of your app and tests on localhost URL’s you must create a test version of your production app. From top-left sidebar create test app. App settings should look like this:
Navigate to Facebook Login product page and make sure you have valid redirect URL in Client OAuth Settings:
Go to test-app dashboard and get client App ID and App Secret — those keys will be used by front-end and back-end of your app.
In this example, I’m using react-apollo as a GraphQL client. It creates HOC that encapsulates API request to my back-end (“mutation” in GrapQL terms). If you are using different back-end (REST for example) you just need to create one “facebookSignIn” method accepting one “code” parameter.
This example renders small widget with the Facebook icon. I’m using it below standard sign-up form:
When the user clicks it he is redirected to:
When the Facebook part is confirmed the user is redirected back to redirect_uri with additional ?code=… parameter.
Component tries to detect code parameter in URL in its constructor (line 12) and then in componentDidMount() callback (line 27) it sends it to back-end.
Back-end’s facebookSignIn mutation replies with user and token information when succeeded so it can be saved in browsers localStorage.
I won’t show how to build GraphQL server, schema, methods — you can find it elsewhere. Here is mutation resolver that processes code from client:
FB is a simple Facebook API wrapper. You can find it here.
This back-end method simply exchanges code parameter from client to short-term access_token allowing you to get Facebook User information. Then we check if we have this user already in a database. Getting long-term access token is optional step — it helps if you plan to get more user information later from Facebook.