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.
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:
httpOnlysecuresameSite: 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, })})You don’t need to obfuscate the cookie name
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
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:
- Use another cookie to hold the expiry value
- Use a JSON cookie
Use another cookie to hold the expiry value
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, })})Remember to include other cookie properties like httpOnly, secure, and
sameSite!
Using a JSON Cookie
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!
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson