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

Saving the access token in cookies

4m:15s

You can save the access token in two places — cookies and local storage.

Whether you use cookies or localStorage depends on whether your frontend is hosted on the same site as the server. Same site here means same domain (including any subdomains).

  • If same site: You can choose between cookies and local storage
  • If not same site: You can only use local storage

I wrote in-depth about the difference between cookies and local storage in an article that may help you decide which to use.

Note

You can use both cookies and local storage. It largely boils down to a matter of preference once you understand how to mitigate security concerns for each method.

You’re going to learn how to store access tokens in cookies in this lesson.

Using Cookies to store access tokens

Storing access tokens with cookies is simple.

To store access tokens, you use the res.cookie method. When you store cookies, I recommend adding three attributes:

  • httpOnly
  • secure
  • sameSite: strict — ensures that this cookie will only be sent to the server if your frontend requests it. This prevents CSRF attacks
router.get('/auth/twitter/callback', async (req, res) => {
const response = await zlFetch.post(/* Get the access token*/)
const { access_token } = response.body
res.cookie('access-token', access_token, {
sameSite: 'strict',
httpOnly: true,
secure: true,
})
})

People may tell you to call the cookie something other than access-token.

You don’t need to do this, because the httpOnly attribute prevents anyone from seeing this token (and hence accessing it). So there’s no point obfuscating the cookie name.

Handling access token expiry values

Access tokens often come with an expiry. You can find the expiry value under the expires_in property. This value is expressed in seconds. For example, Twitter’s access token expires in 7200 seconds.

router.get('/auth/twitter/callback', async (req, res) => {
const response = await zlFetch.post(/* Get the access token*/)
const tokenInfo = response.body
console.log(tokenInfo)
})

You can set a cookie’s expiry value with either the expiry or maxAge attribute. maxAge is easier to use since we can pass in a numeric value in milliseconds.

router.get('/auth/twitter/callback', async (req, res) => {
const response = await zlFetch.post(/* Get the access token*/)
const { access_token, expires_in } = response.body
// Set the cookie's expiry
res.cookie('access_token', access_token, {
// ...
maxAge: expires_in * 1000,
})
})

You can see this expiry value in the browser.

  • For Chrome: Under Applications > Cookies
  • For Firefox: Under Storage > Cookies
Expiry value shown in Firefox

Getting the cookie’s expiry values on the server.

Browsers handle cookie expiry — they delete the cookie when the cookie expires — so they don’t pass the expiry value to the server.

If you need to get the cookie’s expiry value on the server, you can either:

  1. Use another cookie to hold the expiry value
  2. Use a JSON cookie

This is straightforward — you create another cookie to store the expiry value.

Before you do this, you need to calculate the time the access token expires at. This gives us an absolute value like 3pm instead of a relative value like 2 hours later.

router.get('/auth/twitter/callback', async (req, res) => {
// ...
// Calculate the expiry timestamp
const expiresAt = Date.now() + expires_in * 1000
})

Once you have the expiresAt value, you can store the value in a separate cookie. You can also (optionally) add the maxAge property to tell browsers to delete the cookie when it expires.

router.get('/auth/twitter/callback', async (req, res) => {
// ...
res.cookie('access-token', access_token, {
maxAge: expires_in * 1000,
})
// Use another cookie to store the expiry value
res.cookie('access-token-expiry', expiresAt, {
maxAge: expires_in * 1000,
})
})
Note

Remember to include other cookie properties like httpOnly, secure, and sameSite!

You can create a JSON cookie by converting an object into a JSON string.

Of course, you can include a maxAge property if you want the browser to delete the cookie automatically when the token expires.

Here’s what it looks like:

router.get('/auth/twitter/callback', async (req, res) => {
const response = await zlFetch.post(/* Get the access token*/)
const { access_token, expires_in } = response.body
// Creating a JSON value
const jsonCookie = JSON.stringify({
value: access_token,
expiresAt: Date.now() + expires_in * 1000,
})
// Saving a JSON cookie
res.cookie('access-token', jsonCookie, {
// ...
maxAge: expires_in * 1000,
})
})

The cookie-parser library can parse JSON cookies.

To activate this ability, we need to tell cookie-parser the cookie is a JSON cookie. We do this by prepending j: to the cookie value when we create the cookie.

router.get('/auth/twitter/callback', async (req, res) => {
// ...
res.cookie('access-token', `j: ${jsonCookie}`, {
/* ... */
})
})

Cookie parser will read this JSON cookie value and return an object.

router.get('/', (req, res) => {
console.log(req.cookies.accessToken)
})

That’s it!