how to auto refresh access token in google auth library nodejs

1,356 views
Skip to first unread message

chaowen guo

unread,
Dec 6, 2021, 11:33:18 AM12/6/21
to Google Cloud Developers
Hi:

From https://www.npmjs.com/package/google-auth-library, I use the following example:

const {auth} = require('google-auth-library'); // load the environment variable with our keys const keysEnvVar = process.env['CREDS']; if (!keysEnvVar) { throw new Error('The $CREDS environment variable was not found!'); } const keys = JSON.parse(keysEnvVar); async function main() { // load the JWT or UserRefreshClient from the keys const client = auth.fromJSON(keys); client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; const res = await client.request({url}); 

the problem is client.credentials.access_token will expire in 1 hour.

I also see:

Handling token events

This library will automatically obtain an access_token, and automatically refresh the access_token if a refresh_token is present. The refresh_token is only returned on the first authorization, so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the tokens event:

const client = await auth.getClient(); client.on('tokens', (tokens) => { if (tokens.refresh_token) { // store the refresh_token in my database! console.log(tokens.refresh_token); } console.log(tokens.access_token); }); const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; const res = await client.request({ url }); // The `tokens` event would now be raised if this was the first request

But how to combine these two examples together to let client.credentials.access_token auto reflesh?

Aref Amiri (Cloud Platform Support)

unread,
Dec 6, 2021, 2:15:51 PM12/6/21
to Google Cloud Developers
Hi,

I think it is better to post this question on the dedicated Google auth library nodejs Github page, as we do have a dedicated team to help with such issues, or on Stackoverlow page with appropriate tags.  Please note that Google Groups is reserved for general product discussions and is not for technical support.
Reply all
Reply to author
Forward
0 new messages