The SDK’s middleware system provides automatic token management and request/response logging built on top of openapi-fetch. The middleware is internal to the SDK and handles authentication and debugging automatically.

Built-in Middleware

Authentication Middleware

Automatically handles token refresh and authentication for all requests when tokenStorage is provided:

import { StorefrontSDK, BrowserTokenStorage } from '@commercengine/storefront-sdk';

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  apiKey: 'your-api-key',
  tokenStorage: new BrowserTokenStorage() // Enables auth middleware
});

// All requests automatically include valid tokens
const products = await client.catalog.listProducts();

Features:

  • Automatic token refresh before expiry
  • Anonymous token handling with API key
  • Token storage synchronization
  • Seamless authentication state transitions

Debug Middleware

Request/response logging for development when debug mode is enabled:

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  apiKey: 'your-api-key',
  debug: true, // Enable debug middleware
  logger: (level, message, data) => {
    console.log(`[${level}] ${message}`, data);
  }
});

Logged Information:

  • Request URLs, headers, body
  • Response status, headers, body
  • Token refresh events
  • Error details
  • Network timing

Timeout Middleware

Request timeout handling when configured:

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  apiKey: 'your-api-key',
  timeout: 30000 // 30 second timeout
});

Token Storage Integration

The SDK’s automatic token management requires a token storage implementation. For detailed information about all available token storage options, configuration, and best practices, see our comprehensive Token Management Guide.

Quick Setup

import { BrowserTokenStorage } from '@commercengine/storefront-sdk';

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  apiKey: 'your-api-key',
  tokenStorage: new BrowserTokenStorage('my_app_')
});

The token storage you choose affects how the middleware handles authentication. See Token Management for complete storage options including BrowserTokenStorage, CookieTokenStorage, MemoryTokenStorage, and custom implementations.

Authentication Flow

The authentication middleware handles token management automatically:

1

Request Initiated

Client makes API request

2

Token Check

Middleware checks if access token exists and is valid

3

Token Refresh

If token is expired, automatically refreshes using refresh token

4

Storage Update

Updates token storage with new tokens

5

Request Completion

Original request proceeds with valid token

Manual Token Management

Without tokenStorage, tokens must be managed manually:

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  apiKey: 'your-api-key',
  accessToken: 'your-access-token' // Manual token
});

// Update tokens manually
await client.setTokens('new-access-token', 'new-refresh-token');

// Clear tokens manually  
await client.clearTokens();

Framework-Specific Storage

For framework-specific token storage implementations and patterns:

Token Callbacks

React to token changes with callback functions:

const client = new StorefrontSDK({
  storeId: 'your-store-id',
  tokenStorage: new BrowserTokenStorage(),
  onTokensUpdated: (accessToken, refreshToken) => {
    console.log('Tokens updated:', { accessToken, refreshToken });
    // Update app state, analytics, etc.
  },
  onTokensCleared: () => {
    console.log('User logged out');
    // Redirect to login, clear app state, etc.
  }
});

Cross-References

The middleware system is internal to the SDK and automatically configured based on your options. You cannot add custom middleware - the SDK handles authentication, debugging, and timeout management internally.