> ## Documentation Index
> Fetch the complete documentation index at: https://www.commercengine.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Middleware System

> SDK middleware for authentication, token management, and debugging

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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { StorefrontSDK, BrowserTokenStorage } from '@commercengine/storefront';

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

// All requests automatically include valid tokens
const { data, error } = await client.catalog.listProducts();

if (data) {
  console.log(`Successfully fetched ${data.products.length} products.`);
} else if (error) {
  console.error("Failed to fetch products:", error.message);
}
```

**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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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](/docs/sdk/token-management).

### Quick Setup

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { BrowserTokenStorage } from '@commercengine/storefront';

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

<Note>
  The token storage you choose affects how the middleware handles authentication. See [Token Management](/docs/sdk/token-management) for complete storage options including BrowserTokenStorage, CookieTokenStorage, MemoryTokenStorage, and custom implementations.
</Note>

## Authentication Flow

The authentication middleware handles token management automatically:

<Steps>
  <Step title="Request Initiated">
    Client makes API request
  </Step>

  <Step title="Token Check">
    Middleware checks if access token exists and is valid
  </Step>

  <Step title="Token Refresh">
    If token is expired, automatically refreshes using refresh token
  </Step>

  <Step title="Storage Update">
    Updates token storage with new tokens
  </Step>

  <Step title="Request Completion">
    Original request proceeds with valid token
  </Step>
</Steps>

## Manual Token Management

Without `tokenStorage`, tokens must be managed manually:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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:

<CardGroup cols={2}>
  <Card title="Next.js Integration" icon="react" href="/docs/sdk/nextjs-integration">
    Universal token storage for SSR/SSG applications
  </Card>

  <Card title="React Integration" icon="react" href="/docs/sdk/react-integration">
    Browser-based storage with React context patterns
  </Card>
</CardGroup>

## Token Callbacks

React to token changes with callback functions:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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

* **Token Management**: [Token Management Guide](/docs/sdk/token-management) for complete token handling documentation
* **Authentication API**: [Authentication Reference](/docs/api-reference/auth) for endpoint details
* **Storefront Auth Guide**: [Authentication Best Practices](/docs/storefront/authentication) for business logic

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