Prompt
How do I handle API auth refresh in a customer-facing integration?
Latest observation
For a customer-facing integration, the safest pattern is: treat access tokens as short-lived, store refresh tokens securely, and refresh transparently on the server before retrying the failed request.
Here’s a practical approach.
1) Use the right auth model
If customers connect their accounts to your app, usually use:
- OAuth 2.0 Authorization Code flow with PKCE for user-facing integrations
- Refresh tokens for long-lived access
- Short-lived access tokens for API calls
Avoid asking customers to paste API keys unless the provider only supports that.
2) Store tokens securely
Keep tokens server-side, not in the browser or mobile client unless absolutely necessary.
Best practices:
- Encrypt refresh tokens at rest
- Restrict access to token storage
- Separate tokens per tenant/customer/account
- Never log tokens
- Rotate secrets and use least-privilege scopes
3) Refresh proactively, not just reactively
Two common strategies:
A. Proactive refresh
Refresh before the access token expires:
- Track
expires_at - Refresh a few minutes early
- Good for reducing failed requests
B. Reactive refresh
If an API call returns:
401 Unauthorizedinvalid_token- token-expired error
Then:
- pause/retry once
- refresh the token
- retry the original request
Best practice is usually proactive + reactive fallback.
4) Prevent refresh races
A common bug: multiple requests fail at once and all try to refresh, causing:
- duplicate refresh calls
- token overwrite
- refresh token rotation issues
Use a single-flight / mutex / lock per connected account so only one refresh happens at a time.
Pseudo-flow:
- Request fails with auth error
- Check if another refresh is already in progress
- If yes, wait for it
- If no, perform refresh
- Store new tokens atomically
- Retry the original request once
5) Handle refresh-token rotation
Some providers issue a new refresh token every time you refresh.
Important:
- Always save the newest refresh token returned
- Update atomically with the access token
- If refresh fails with
invalid_grant, the old refresh token may already be rotated or revoked
If you ignore rotation, your integration can break randomly after the next refresh.
6) Plan for token expiration and revocation
Don’t assume refresh will always work.
Have clear handling for:
- user revoked consent
- password changed
- account disabled
- refresh token expired
- scope changed
When refresh fails permanently:
- mark the integration as disconnected
- notify the customer
- prompt them to re-authenticate
7) Be careful with retries
Only retry once after refresh. Otherwise you can end up in loops.
Example:
- API call fails with 401
- refresh succeeds
- retry original request
- if it fails again with auth error, stop and surface reauth required
8) Add observability
Track:
- refresh success/failure rate
- invalid_grant errors
- token expiry timestamps
- number of reauth prompts
- provider-specific error codes
This helps spot outages or bad token handling early.
9) Customer-facing UX tips
Make the experience understandable:
- “Connection needs to be reauthorized” instead of “token invalid”
- Show which account/integration is affected
- Offer a one-click reconnect flow
- Warn before access expires if the provider supports it
10) A simple implementation pattern
A good server-side wrapper looks like:
- Load token for customer/integration
- If access token is near expiry, refresh first
- Call provider API
- If request returns auth error, refresh once and retry
- If refresh fails, mark integration disconnected
11) If you’re building this in a multi-tenant app
Use a per-connection token record like:
customer_idprovideraccess_token_encryptedrefresh_token_encryptedexpires_atscopesstatuslast_refresh_at
And ensure token refresh updates happen in a transaction or atomic write.
If you want, I can give you:
- a language-agnostic refresh wrapper,
- a Node/Python example, or
- a recommended database schema for storing integration tokens.