google-auth-library-nodejs
google-auth-library-nodejs copied to clipboard
Refresh the token in an AWS Lambda function
The library works perfectly on my machine but when it's deployed in a Lambda function, the token doesn't seem to automatically update:
export const getAuthenticatedGoogleClient = async (
userId: string,
credentialsId: string
): Promise<OAuth2Client | undefined> => {
const credentials = (await prisma.credentials.findFirst({
where: { id: credentialsId, ownerId: userId },
})) as CredentialsFromDb | undefined
oauth2Client.setCredentials(credentials)
oauth2Client.on('tokens', updateTokens(credentialsId))
return oauth2Client
}
const updateTokens = (credentialsId: string) => async (credentials) =>
prisma.credentials.update({
where: { id: credentialsId },
data: { credentials },
})
My guess is that it doesn't have time to update in the database because this is handled in a callback.
Is there a way to check if expiry_date is passed and update the token with a Promise-based function?
Some examples of errors I get:
Oooooh I think I know, I think the tokens from the callback don't contain the refresh_token
so I pushed credentials in db without the refresh_token
!
Hey, apologies for the delay - I would recommend storing the refresh_token
when it is available in the callback (usually, the initial authorization):
- https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450
Here's some documentation as well: https://github.com/googleapis/google-auth-library-nodejs#handling-token-events