Vue Storefront is now Alokai! Learn More
Refresh token and retry mechanism

Refresh token and retry mechanism

Introduction

This guide explains how the SAPCC integration within our SDK handles HTTP 401 (Unauthorized) errors. The integration is designed to automatically retry requests when a 401 error occurs, after refreshing the authentication token. This process ensures a smoother and more resilient interaction with the SAPCC services.

Mechanism Overview

When a request to SAPCC returns a 401 error, indicating an expired or invalid token, the SDK will:

  1. Automatically invoke a token refresh process.
  2. Once the token is refreshed, retry the original request with the new token.
  3. If the token refresh fails, it handles the error based on the provided configuration.

Configurable Options

The behavior of this mechanism is configurable through the following options:

RefreshTokenCallbacks

  • onTokenRefreshed(refreshTokenResponse: any) => Promise<void>: This callback is invoked when the token is successfully refreshed. You can use it to handle the new token, for example, updating the client's state.
  • onTokenRefreshError(error: any) => Promise<void>: Invoked when an error occurs while refreshing the token, allowing you to handle this scenario, like logging or triggering alerts.

RefreshTokenAndRetryOptions

  • ssrRefreshEnabled: boolean: A flag to enable the mechanism during server-side rendering (SSR). By default, the mechanism is disabled during SSR, as the cookies are not sent by default and we advise against using customer-token-dependent requests on the server side. If you enable this option, you must ensure that the token is stored in the cookies manually in the onTokenRefreshed callback.
  • isUnauthorized(error: any) => boolean: A function to determine if an error is an unauthorized error.
  • refreshTokenMethod(...args: any[]) => Promise<any>: The method that will be used to refresh the token.
  • callbacks: RefreshTokenCallbacks: Specifies the callbacks for token refresh events.

Example Configuration

Configuration in the Alokai Storefront has been described in Automatically Refreshing Access Tokens guide.