Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Understanding Async JS
Lesson Plan
  1. Introduction
    1. What is Asynchronous JS?
    2. Callbacks are not automatically asynchronous
    3. What is an API?
    4. Evolution of HTTP APIs
    5. Ajax vs Asynchronous JavaScript
  2. Fundamental Concepts
    1. How to fetch resources
    2. Using XHR
    3. Using the Fetch API
    4. Using libraries
    5. Core JavaScript concepts
    6. Understanding Promises
    7. Understanding Async Functions
    8. Understanding the Event Loop
    9. Understanding JSON
    10. Async JS Best Practices
    11. Using Optimistic UI
  3. Understanding Rest API
    1. Diving into Rest APIs
    2. The Rest Architecture
    3. The Rest Structure
    4. Anatomy of a Request
    5. What's an endpoint
    6. Request methods
    7. Understanding request headers
    8. Understanding the request body
    9. Authentication
    10. Basic Authentication
    11. Bearer Authentication
    12. Authenticating with API keys and API Secrets
    13. Cross Origin Resource Sharing
    14. Anatomy of a response
    15. HTTP Statuses
    16. Response headers
    17. The response body
    18. Handling Errors
    19. Reading API documentations
    20. Understanding Curl
  4. Node Basics
    1. Why we are using Node
    2. Command Line Basics
    3. Installing Node
    4. Managing dependencies
    5. Using ES Modules in Node
    6. Using Node
    7. Restarting the server automatically
    8. Sending requests via Node
    9. Protecting API keys and secrets
  5. Building a server
    1. What's a server
    2. Building a simple server with Express
    3. Two kinds of servers
    4. API Server architecture
    5. Handling routes
    6. Understanding Middlewares
    7. Enabling CORS
    8. Receiving data
    9. Sending responses
    10. Handling errors in Express
    11. Using the server as a proxy
    12. Minimum viable server
  6. Open Authorization
    1. Open Authorisation (OAuth)
    2. Authenticating with Access Tokens
    3. Obtaining Access Tokens
    4. Public and Confidential Clients
    5. Authorisation Code Grant
    6. Understanding scope
    7. Proof Key for Code Exchange (PKCE)
    8. PKCE with Twitter
    9. Dynamic state and `code_verifier`
    10. Saving the access token in cookies
    11. Passing access tokens to the browser
    12. Saving the access token in local storage
    13. Refresh Token Grant
    14. Device Code Grant
    15. Client libraries vs REST
  7. Building Social Media Logins
    1. Introduction
    2. Starter Files
    3. Creating SSL certificates
    4. Login in with Github
    5. Github: Saving the token to local storage
    6. Github: Persisting the login status
    7. Login with Twitter
    8. Twitter: Saving the token to local storage
    9. Twitter: Persisting the login status
    10. Twitter: Refreshing the access token
    11. Login with Facebook
    12. Facebook: Saving the token to localStorage
    13. Facebook: Persisting the login status
    14. Facebook: Refreshing the access token
    15. Login with google
    16. Google: Saving the token to localStorage
    17. Google: Refreshing the access token

Login with Facebook

We’re moving onto something completely new now!

In this lesson, you will learn to login with Facebook.

Again, the same four steps apply:

  1. Create the app
  2. Create the sign-in link
  3. User logs in on Facebook
  4. Exchange code for access token

Create the app

Here are the instructions to create the app for facebook.

You can name the app anything you want.

  • I named it Social Media Login App.
  • We’re going to set callbackURL to https://localhost/auth/facebook/callback.

Before you move on, make sure you add your facebook credentials to the .env file.

Terminal window
FACEBOOK_CLIENT_ID="Your Client ID"
FACEBOOK_CLIENT_SECRET="Your Client Secret"

When the user clicks the sign-in link, we will redirect the user to facebook. We can do this in two steps:

  1. We direct the user to an endpoint in our server.
  2. In this endpoint, we redirect the user to facebook.
<!-- Direct user to endpoint in our server -->
<a href="/auth/facebook" ...> Login with Facebook </a>

In this endpoint, we craft the sign-in link for facebook.

Here are the instructions from Facebook.

If you read this page, you will notice that Facebook subtly hints that there are two required parameters — state and redirect_uri

Here’s how you create the sign-in link.

router.get('/auth/facebook', async (req, res) => {
const { state } = await PKCE()
const baseURL = 'https://www.facebook.com/v15.0/dialog/oauth'
const params = {
client_id: process.env.FACEBOOK_CLIENT_ID,
redirect_uri: 'https://localhost/auth/facebook/callback',
state,
}
const query = new URLSearchParams(params)
const link = baseURL + '?' + query.toString()
})

Since Facebook requires state, we need to save state into the cookies.

router.get('/auth/facebook', async (req, res) => {
// ...
res.cookie('state', state, { httpsOnly: true, secure: true })
})

Then we redirect the user to Facebook.

router.get('/auth/facebook', async (req, res) => {
// ...
res.redirect(link)
})

User logs in to facebook

Nothing for us to do here :)

Exchange code for access token

When the user authorise the Facebook login, Facebook will redirect them back to /auth/facebook/callback.

We need to take a couple of steps here:

  1. Check whether state is valid
  2. Grab code from the url.
  3. Send a request to facebook to get the access token

Checking whether state is valid

We need to grab both state from the callback url and state from the cookies. We’ll check whether they are the same value before we proceed with the rest of the steps.

router.get('/auth/facebook/callback', async (req, res) => {
const { state: returnedState } = req.query
const { state } = req.cookies
if (state !== returnedState) return
})

Grabbing code from the url

We need to grab code from the callback URL because we need to send it to facebook.

router.get('/auth/facebook/callback', async (req, res) => {
const { state: returnedState, code } = req.query
const { state } = req.cookies
if (state !== returnedState) return
})

Send a request to facebook

Then we send this code to Facebook’s token endpoint to get the access token.

Here are the instructions from Facebook.

Notice two things here:

  1. Facebook uses a GET request (while others we’ve worked on so far use a POST) request for the endpoint.
  2. Required parameters are client_id, redirect_uri, client_secret and code.

These two points means we can generate the following request:

router.get('/auth/facebook/callback', async (req, res) => {
// ...
const response = await zlFetch(
'https://graph.facebook.com/v15.0/oauth/access_token',
{
query: {
client_id: process.env.FACEBOOK_CLIENT_ID,
client_secret: process.env.FACEBOOK_CLIENT_SECRET,
redirect_uri: 'https://localhost/auth/facebook/callback',
code,
},
},
)
const token = response.body
console.log(token)
})

You should receive a token like this:

The user is now logged in.

Handling the access token

We’re going to store the access token in Local Storage in the next lesson.