Refresh an access token
Renew the access token of a Login client with its refresh token before the access token expires, without another login redirect.
expires_in in the token response gives the lifetime of the access token in
seconds. An API client gets no refresh token and requests another access token
with its client ID and secret instead.
Prerequisites
- A refresh token from the token response of a Login client.
- A
clearAppTokens()function that clears the token storage of your app.
Steps
-
Start one refresh request at a time.
-
Send the refresh token to
token_endpointwith therefresh_tokengrant:const res = await fetch( "https://www.remilia.net/oidc/realms/remilia/protocol/openid-connect/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", client_id: "YOUR_CLIENT_ID", refresh_token: storedRefreshToken, }), }, ); const result = await res.json(); if (!res.ok) { if (result.error === "invalid_grant") { clearAppTokens(); throw new Error("Session expired. Log in again."); } throw new Error("Token refresh failed. Retry later."); } // The result holds an access_token and can hold a refresh_token. const tokens = result; -
If the user logged out or started another login, discard the response.
-
Save the access token from the response.
-
If the response includes a replacement refresh token, save it.
-
If refresh returns
invalid_grant, start another login from the authorization redirect. -
If a request fails temporarily, retry later with the stored refresh token.
Result
Your app holds a fresh access token. A rotated refresh token replaces the
earlier one. A temporary failure keeps the stored refresh token, and
invalid_grant clears the local tokens.
Next steps
For the storage choices and the refresh rules, see Token and session security.
