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

Facebook: Refreshing the access token

We know that Facebook has an access token that lasts for a long time — 5183280 seconds (which is approximately 60 days).

Previously, we can invalidate Twitter’s access token since we can use the refresh token to generate a new access token.

But with Facebook, we have a different problem — we cannot invalidate the access token because there is no refresh token to use!

After digging around Facebook’s documentation, I found that you can generate a new access token with the current access token.

Further, under the caveats, we can see that you cannot use an expired token to request for a new access token.

This means:

  1. We cannot change accessToken — because we cannot generate a new one without a valid accessToken
  2. We cannot change expiresAt — because Facebook does not let you generate a new access token with an expired access token.

If we really want to update the access token, we need a valid access token to work with. We can:

  1. Update the access token on every single page load — which is a bit excessive…
  2. Update the access token once a day — this is what Facebook does in their SDK.
  3. Or update the access token a couple of days before it expires — this is not ideal because the user may not log in for the last few days.

We’ll follow Facebook’s implementation.

Refreshing the access token

In persist-state.js, we need to make sure Facebook’s access token code is able to get to the /auth/provider/refresh even though the access token is still valid.

We can do it with the following code:

providers.forEach(async provider => {
// ...
// For Facebook, we need to refresh the token every day so it needs to continue on to the next step. For everything else, we can stop here.
if (isValid && provider !== 'facebook') return
const { response } = await zlFetch.post(`/auth/${provider}/refresh`, {
/**/
})
// ...
})

We need to pass Facebook’s access token to the /auth/facebook/refresh endpoint.

providers.forEach(async provider => {
// ...
const { response } = await zlFetch.post(`/auth/${provider}/refresh`, {
body: { refreshToken, accessToken },
returnError: true,
})
// ...
})
Note

We continue to send a refreshToken because we need it to refresh Twitter’s access token. We’ll handle the difference in data in our backend.

Now we need to create the /auth/facebook/refresh endpoint in our backend.

router.post('/auth/facebook/refresh', async (req, res) => {
// ...
})

And we can refresh the access token with the following code:

router.post('/auth/facebook/refresh', async (req, res) => {
const { accessToken } = req.body
const { response, error } = await zlFetch(
'https://graph.facebook.com/oauth/access_token',
{
query: {
grant_type: 'fb_exchange_token',
client_id: process.env.FACEBOOK_CLIENT_ID,
client_secret: process.env.FACEBOOK_CLIENT_SECRET,
fb_exchange_token: accessToken,
},
returnError: true,
},
)
console.log(response.body)
// ...
})

Here’s what Facebook returns when we send the above request:

This part should be simple for you now. We can need to send the access token and expiresAt to the frontend… and we can do it with the following code.

router.post('/auth/facebook/refresh', async (req, res) => {
// ...
if (response) {
const token = response.body
const expiresAt = token.expires_in * 1000 + Date.now()
const params = {
expiresAt,
accessToken: token.access_token,
}
res.json(params)
}
if (error) {
res.status(error.status).json({ error: error.message })
}
})

If you do this correctly… Facebook should now have a new access token when you refresh the page.

The next step is to refresh the token once a day

Refreshing the token once a day

We need to check whether we should refresh the facebook token before we send the request to refresh the token.

providers.forEach(async provider => {
// ...
// Code to check whether we should refresh
// facebook token should go here
// And we refresh the token here
const { response } = await zlFetch.post(`/auth/${provider}/refresh`, {
body: { refreshToken, accessToken },
returnError: true,
})
// ...
})

There are a couple of conditions to check this. The easiest and cleanest way is to check the code through a separate function. We’ll create a function called shouldRefreshFacebookToken and use it.

providers.forEach(async provider => {
// ...
// Check whether to refresh Facebook's access token
const shouldRefreshFBToken = shouldRefreshFacebookToken()
if (provider === 'facebook' && !shouldRefreshFBToken) return
// And we refresh the token here
const { response } = await zlFetch.post(`/auth/${provider}/refresh`, {
body: { refreshToken, accessToken },
returnError: true,
})
// ...
})

There are a couple of things we need to check in shouldRefreshFacebookToken.

First, we need a way to know when we last checked the token. This means we can save the data in a new local storage key. If we saved it, we should be able to retrieve it with localStore

If we did not save the last checked date to local storage, it means we have not refreshed to the token yet — and we should refresh the token.

function shouldRefreshFacebookToken() {
const lastCheckedDate = localStore.get('facebook_refresh_last_check_date')
if (!lastCheckedDate) return true
}

Before we return true, we need to make sure we update the last checked date — so we can use it for future checks.

function shouldRefreshFacebookToken() {
const lastCheckedDate = localStore.get('facebook_refresh_last_check_date')
const now = Date.now()
localStore.set('facebook_refresh_last_check_date', now)
if (!lastCheckedDate) return true
}

Now we can proceed and check whether we’ve checked for a refresh within the last 24 hours.

  • If we didn’t, we need to refresh the token.
  • If we did, we don’t have to refresh the token.
function shouldRefreshFacebookToken() {
// ...
// Refresh Facebook token every 24 hours
const oneDay = 1000 * 60 * 60 * 24 // 1 day in milliseconds
if (now - lastCheckedDate >= oneDay) return true
// If we checked in the last 24 hours, we don't need to refresh the token
return false
}

Try refreshing your browser multiple times. You should see the last checked date change, but the Facebook access token should not change.

We’re done with Facebook.

Let’s go refactor some code before we proceed to the final identity provider.