Before we can save the token to Local Storage, we need to send the token to the browser.
We’re going to use the query string method to be consistent with what we have done with Github.
Sending token to frontend via the query string
First, we need to determine which values we need to send to the frontend.
From the Github lesson, you already know we need to send at least three values:
authStatus— so we know whether the authentication is successfulprovider— so we know it’s from Github and not other identity providers.access_token— so we know can save the access token in Local Storage.
Let’s take a look at the token Twitter sends back to us and see if we need to include more values.
We can see that expires_in is 7200 minutes. This means the access token will expire in 2 hours. We need to send this value to the frontend so we know whether the access token has expired.
But we cannot use the 7200 value because that’s a relative number. We need to convert it to an exact date before we send it to the frontend.
const expiresAt = token.expires_in * 1000 + Date.now()We also need to send the refresh_token to the frontend because we don’t have a database to save the refresh_token in this app.
In an actual app, you would NOT want to send the refresh_token to the
frontend to minimize security vulnerabilities. You want to keep the
refresh_token in the database instead.
So in this case we need to send five values:
authStatusprovideraccess_tokenexpiresAtrefresh_token
Here’s how you can do this.
router.get('/auth/github/callback', async (req, res) => { // ... const token = response.body const expiresAt = token.expires_in * 1000 + Date.now()
// Sends the token to the browser to be stored in Local Storage const params = { authStatus: 'success', provider: 'twitter', expiresAt, access_token: token.access_token, refresh_token: token.refresh_token, }
const query = new URLSearchParams(params).toString() res.redirect('/' + '?' + query)})Getting the token from query parameters
We need to get the refresh_token and expiresAt values from the query string as well. So let’s add them to save-token.js.
if (searchParams.get('authStatus') === 'success') { // ... const refreshToken = searchParams.get('refresh_token') const expireAt = searchParams.get('expiresAt') // ...}Saving the tokens
We can save the information in local storage like this:
if (searchParams.get('authStatus') === 'success') { // ...
localStore.set(provider, { accessToken, refreshToken, expiresAt })}You should be able to see these three values for Twitter in your local storage.
We are done saving the token. Let’s move on to the next step.
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