OAuthToken structure, the token methods on the SWCombine client, automatic token refresh, and patterns for persisting tokens across server restarts.
The OAuthToken object
Every method that returns a token uses theOAuthToken interface:
expiresAt is a millisecond epoch value. Compare it with Date.now() to check whether the token has expired, or let the SDK do this automatically.
Access tokens typically expire after one hour. Refresh tokens are long-lived but have no
guaranteed expiry from the SDK side — store and protect them accordingly.
Token methods on the client
These methods are available on anySWCombine instance:
setToken
Sets the active token. Accepts either a raw access token string or a fullOAuthToken object. When you pass a string, the SDK wraps it in an OAuthToken with a 1-hour assumed expiry.
getToken
Returns the currentOAuthToken object, or null if no token is set.
clearToken
Removes the active token from the client. After calling this, any authenticated request will fail until you set a new token.isTokenExpired
Returnstrue if the current token’s expiresAt is in the past, or if no token is set.
hasRefreshToken
Returnstrue if the current token includes a refreshToken value.
Automatic token refresh
When you initialize the client in full OAuth mode (withclientId and clientSecret) and the current token includes a refreshToken, the SDK refreshes automatically. It checks the token before every request and refreshes proactively if the token is expired or will expire within the next 5 minutes.
- The client was initialized with
clientIdandclientSecret. - The current
OAuthTokenincludes arefreshToken(i.e., you usedAccessType.Offlineduring authorization).
SWCError with type auth rather than silently failing.
Manual token refresh
Callclient.refreshToken() to trigger a refresh immediately, regardless of expiry state. This is useful if you want to pre-fetch a fresh token before a batch job or proactively rotate before expiry:
refreshToken() requires both OAuth credentials and an active refresh token. It throws SWCError if either is missing.
Proactive refresh before expiry
To avoid any disruption during long-running tasks, you can schedule a refresh before the token expires:Custom token persistence
The SDK stores tokens in memory by default. If you restart your server, you lose the token and the user must re-authorize. To avoid this, save the token to a database after authorization and restore it on startup:SWCombine instance per request rather than sharing one client across users:
Handling token expiration errors
Even with automatic refresh configured, you should handle401 Unauthorized responses gracefully — for example, when a refresh token itself has been revoked: