When integrating Google OAuth2 in your Node.js / Next.js app using the googleapis library, a key question is:
π§ "How do I handle access token expiration and refresh automatically?"
Turns out β you don't need to handle much at all. But understanding why and how took me down a rabbit hole. Here's what I learned so you don't get stuck like I did.
π The Basics
When you authorize a user via the OAuth2 web server flow (access_type: "offline"
), Google returns:
- access_token β short-lived, used for API requests
- refresh_token β used to get a new access token
- expiry_date β timestamp (in ms) when the access token expires
β The Simple Solution
The good news? You can make Google auto-refresh tokens just by doing this:
oauth2Client.setCredentials({
access_token,
refresh_token,
expiry_date,
});
Then, call the API like normal:
const calendar = google.calendar({ version: "v3", auth: oauth2Client });
await calendar.events.delete({
calendarId: "primary",
eventId: "123",
});
If the access_token
is expired, the client automatically refreshes it using the refresh_token
.
π No need to manually check expiry or refresh!
π€ Then Why Do People Use getAccessToken()?
Great question!
Use getAccessToken()
only when you need the raw token string, such as:
- Adding it to custom headers
- Injecting into a GraphQL/WebSocket context
- Logging / debugging
const { token } = await oauth2Client.getAccessToken();
Otherwise, skip it. Google handles everything internally during requests.
π§ͺ How I Tested the Refresh Behavior
Want to test token refresh manually without waiting for expiration?
Just fake the expiry like this:
oauth2Client.setCredentials({
access_token,
refresh_token,
expiry_date: Date.now() - 1000, // fake it as expired
});
Then make a normal API call β it will refresh in the background.
π Bonus: Log When Token Refresh Happens
You can log when a refresh happens using the tokens
event:
oauth2Client.on("tokens", (tokens) => {
console.log("π Refreshed tokens:", tokens);
});
Perfect for debugging or confirming it's working.
π§ Lessons Learned
- The docs are technically right, but don't show everything clearly
- The googleapis package uses google-auth-library internally, which handles refresh logic
- Set a past
expiry_date
+ make a request = auto-refresh - Use
getAccessToken()
only when you need the token string - You don't need to memorize class hierarchies β but checking inheritance (like OAuth2Client β AuthClient) helps
π Final Tip
If you're ever unsure about how a client like OAuth2Client behaves:
- Look for event hooks (like
tokens
) - Check method docs (
getAccessToken
,request
) - Look at class inheritance
- Test locally with fake expiry
Top comments (0)