someone who's managed to maintain an OAuth2 refresh_token for google api before, could I compare code with you? The docs say that if I create an access_token with access_type:"offline", the client api will automatically use the refresh_token before expiry, but in my case this happens only once, at which time the refresh_token disappears from the updated token object. My code's as simple as this:
async function google(request)
{let [{google},keys]=await Promise.all(
[import("./node_modules/googleapis/build/src/index.js")
,import("./keys.json").then(json=>json.default)
]);
let {client,secret,token}=keys;
let authority=new google.auth.OAuth2(client,secret,request.url);
authority.on('tokens',token=>save("keys.json",{...keys,token}).then(console.log));
if(!token)
if(!request.query.code)
return authority.generateAuthUrl({scope,access_type:"offline",prompt:"consent"});
else return new Promise(resolve=>
authority.getToken(request.query.code,resolve)).then(fail=>fail||"new access_token");
authority.setCredentials(token);
google=google.sheets({version:"v4",auth:authority});
return new Promise(resolve=>
google.spreadsheets.values.get(sheet,resolve)).then(fail=>fail||"valid token");
// first return value: [consent url redirecting to the same endpoint]
// after using the url: "new access_token"
// during the next 2 hours: "valid token" ("refresh_token" gone missing from keys.json in the second hour)
// after 2 hours: "Error: missing required parameter: refresh_token"
}
could it be because I'm dynamically reinstantiating the API on each request? I'm setting the credentials each time too, so it shouldn't make a difference to having a static API
My realisation commenting on DalmTo's answer proved to be the answer: the refresh_token for an access_token is static, so the issue is when saving the new token, the refresh_token has to be preserved. This might be useful to mention in the docs as well, unless it is, and I just missed this detail.