'How to handle Refesh-Tokens with GoogleApis for NodeJS Client?

I'm looking at the following documentation: https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens

Especially this part:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});

What I don't understand is why I should store the refresh-token in a database. Is it due to that the refresh-token is only provided to me on the first authorization? But even so, shouldn't that mean that this part:

oauth2Client.setCredentials({
  refresh_token: `STORED_REFRESH_TOKEN`
});

should replace the comment above (// store the refresh_token in my database!)? A.K.A:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    oauth2Client.setCredentials({
  refresh_token: tokens.refresh_token
  });
});

This due to Google's statement in the documentation: "This library will automatically use a refresh token to obtain a new access token if it is about to expire".

What I want to build is an application where people login with their Google-account and then can use several analytics tools I build utilizing f.e Google-analytics API.

I've managed via the documentation to set a valid access-token, but I'm really interested in this topic and really want to learn the refresh-part but have a really hard time wrapping my head around it. If someone could help me understand, I would be really greatful. If not, could someone point me to a great explanation of this (for nodejs) elsewhere? :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source