Skip to content

Authentication and sessions

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

  1. Start one refresh request at a time.

  2. Send the refresh token to token_endpoint with the refresh_token grant:

    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;
  3. If the user logged out or started another login, discard the response.

  4. Save the access token from the response.

  5. If the response includes a replacement refresh token, save it.

  6. If refresh returns invalid_grant, start another login from the authorization redirect.

  7. 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.