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

# Configuration

> Complete guide to configuring the TypeScript SDK for different environments and use cases

The StorefrontSDK provides extensive configuration options to fit any environment or use case, from simple prototyping to complex production deployments.

## Basic Configuration

### Minimal Setup

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

const sdk = createStorefront({
  storeId: "your-store-id",      // Required
  apiKey: "your-api-key"         // Required for anonymous authentication
});
```

### Production Setup

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

const sdk = createStorefront({
  storeId: process.env.NEXT_PUBLIC_STORE_ID!,
  environment: Environment.Production,
  apiKey: process.env.NEXT_PUBLIC_API_KEY!,
  tokenStorage: new CookieTokenStorage({
    prefix: "myapp_",
    secure: true,
    sameSite: "Lax"
  }),
  timeout: 15000,
  debug: false
});
```

## Configuration Options

### Core Configuration

<ParamField path="storeId" type="string" required>
  Your unique store identifier from the Commerce Engine dashboard.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "01ABCD1234567890ABCDEFG", // Your store ID
    // ... other options
  });
  ```
</ParamField>

<ParamField path="apiKey" type="string" required>
  API key for authentication endpoints. Required for anonymous authentication and initial token acquisition.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    apiKey: "sk_live_abcdef1234567890", // Production API key
    // ... other options
  });
  ```
</ParamField>

### Environment Management

<ParamField path="environment" default="Environment.Production" type="Environment">
  Target environment for API requests. Controls which API endpoints are used.

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

  const sdk = createStorefront({
    storeId: "your-store-id",
    environment: Environment.Staging, // or Environment.Production
    // ... other options
  });
  ```

  **Available Environments:**

  * `Environment.Production` → `https://prod.api.commercengine.io/api/v1/{storeId}/storefront`
  * `Environment.Staging` → `https://staging.api.commercengine.io/api/v1/{storeId}/storefront`
</ParamField>

<ParamField path="baseUrl" type="string">
  Custom base URL that overrides the environment setting. Useful for on-premise deployments or custom endpoints.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    baseUrl: "https://api.mycompany.com/v1/storefront", // Custom URL
    // ... other options
  });
  ```

  <Warning>
    When `baseUrl` is provided, the `environment` setting is ignored. Ensure your custom URL follows the correct API path structure.
  </Warning>
</ParamField>

### Token Management

<ParamField path="accessToken" type="string">
  Initial access token for manual token management or as a starting token for automatic management.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    accessToken: "eyJhbGciOiJIUzI1NiIs...", // JWT access token
    // ... other options
  });
  ```

  **Behavior:**

  * **With tokenStorage**: Used as initial token, then managed automatically
  * **Without tokenStorage**: Used for manual token management
</ParamField>

<ParamField path="refreshToken" type="string">
  Initial refresh token. Only used when `tokenStorage` is provided for automatic token management.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    accessToken: "eyJhbGciOiJIUzI1NiIs...",
    refreshToken: "eyJhbGciOiJIUzI1NiIs...", // Only used with tokenStorage
    tokenStorage: new BrowserTokenStorage(),
    // ... other options
  });
  ```
</ParamField>

<ParamField path="tokenStorage" type="TokenStorage">
  Token storage implementation for automatic token management. See [Token Management](/sdk/token-management) for detailed information.

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

  const sdk = createStorefront({
    storeId: "your-store-id",
    tokenStorage: new BrowserTokenStorage("myapp_"),
    // ... other options
  });
  ```
</ParamField>

### Request Configuration

<ParamField path="timeout" default="undefined" type="number">
  Request timeout in milliseconds. When not set, uses the default fetch timeout behavior.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    timeout: 15000, // 15 seconds
    // ... other options
  });
  ```

  <Tip>
    **Recommended timeouts:**

    * **Development**: 30000ms (30 seconds) for easier debugging
    * **Production**: 10000ms (10 seconds) for better user experience
    * **Server-side**: 5000ms (5 seconds) for API routes
  </Tip>
</ParamField>

<ParamField path="defaultHeaders" type="SupportedDefaultHeaders">
  Default headers applied to all API requests. These can be overridden at the method level.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    defaultHeaders: {
      customer_group_id: "01JHS28V83KDWTRBXXJQRTEKA0" // For pricing & promotions
    },
    // ... other options
  });
  ```

  **Supported Headers:**

  * `customer_group_id`: Used for customer-specific pricing, promotions, and subscription rates
</ParamField>

### Debugging & Logging

<ParamField path="debug" default="false" type="boolean">
  Enable detailed request/response logging for development and troubleshooting.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    debug: true, // Enable debug logging
    // ... other options
  });
  ```

  **Debug Information Includes:**

  * Request URLs, methods, headers, and bodies
  * Response status, headers, and bodies
  * Token refresh attempts and results
  * Network errors and retry attempts
</ParamField>

<ParamField path="logger" type="DebugLoggerFn">
  Custom logger function for debug information. If not provided and debug is enabled, uses `console.log`.

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const sdk = createStorefront({
    storeId: "your-store-id",
    debug: true,
    logger: (level, message, data) => {
      // Custom logging logic
      console.log(`[${level.toUpperCase()}] ${message}`);
      if (data) console.table(data);
    },
    // ... other options
  });
  ```

  **Logger Interface:**

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  interface DebugLoggerFn {
    (level: "info" | "warn" | "error", message: string, data?: any): void;
  }
  ```
</ParamField>

## Framework-Specific Configurations

For detailed framework integration patterns including token storage, context setup, and best practices, see our dedicated guides:

<CardGroup cols={2}>
  <Card title="Next.js Integration" icon="code" href="/sdk/nextjs-integration">
    SSR/SSG compatible configuration with automatic token management
  </Card>

  <Card title="TanStack Start Integration" icon="code" href="/sdk/tanstack-start-integration">
    Server functions, route loaders, and pre-rendering
  </Card>

  <Card title="React Integration" icon="code" href="/sdk/react-integration">
    Client-side configuration with context providers and hooks
  </Card>

  <Card title="Node.js Integration" icon="server" href="/sdk/nodejs-integration">
    Server-side configuration for API routes and background jobs
  </Card>

  <Card title="Token Management" icon="key" href="/sdk/token-management">
    Complete guide to automatic token management and storage options
  </Card>
</CardGroup>

### Quick Examples

Basic configuration examples for different environments:

<Tabs>
  <Tab title="Client-Side (React/Vue)">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { StorefrontSDK, BrowserTokenStorage, Environment } from "@commercengine/storefront";

    const sdk = createStorefront({
      storeId: process.env.REACT_APP_STORE_ID!,
      environment: Environment.Production,
      apiKey: process.env.REACT_APP_API_KEY!,
      tokenStorage: new BrowserTokenStorage("myapp_")
    });
    ```
  </Tab>

  <Tab title="Server-Side (Node.js)">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { StorefrontSDK, MemoryTokenStorage, Environment } from "@commercengine/storefront";

    const sdk = createStorefront({
      storeId: process.env.STORE_ID!,
      environment: Environment.Production,
      apiKey: process.env.API_KEY!,
      tokenStorage: new MemoryTokenStorage()
    });
    ```
  </Tab>

  <Tab title="Universal (Next.js)">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import { StorefrontSDK, CookieTokenStorage, Environment } from "@commercengine/storefront";

    const sdk = createStorefront({
      storeId: process.env.NEXT_PUBLIC_STORE_ID!,
      environment: Environment.Production,
      apiKey: process.env.NEXT_PUBLIC_API_KEY!,
      tokenStorage: new CookieTokenStorage({ prefix: "myapp_" })
    });
    ```
  </Tab>
</Tabs>

## Advanced Configuration Patterns

### Multi-Tenant Configuration

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
interface TenantConfig {
  storeId: string;
  environment: Environment;
  apiKey: string;
  customDomain?: string;
}

class MultiTenantSDK {
  private sdks: Map<string, StorefrontSDK> = new Map();
  
  getSDK(tenantId: string, config: TenantConfig): StorefrontSDK {
    if (!this.sdks.has(tenantId)) {
      const sdk = createStorefront({
        storeId: config.storeId,
        environment: config.environment,
        apiKey: config.apiKey,
        baseUrl: config.customDomain 
          ? `https://${config.customDomain}/api/v1/storefront`
          : undefined,
        tokenStorage: new BrowserTokenStorage(`tenant_${tenantId}_`),
        timeout: 10000
      });
      
      this.sdks.set(tenantId, sdk);
    }
    
    return this.sdks.get(tenantId)!;
  }
}

// Usage
const multiTenant = new MultiTenantSDK();
const tenantASDK = multiTenant.getSDK("tenant-a", {
  storeId: "store-a",
  environment: Environment.Production,
  apiKey: "key-a"
});
```

### Configuration Factory

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
interface SDKEnvironment {
  name: string;
  storeId: string;
  apiKey: string;
  environment: Environment;
  baseUrl?: string;
}

class SDKConfigFactory {
  private environments: Record<string, SDKEnvironment> = {
    development: {
      name: "Development",
      storeId: process.env.DEV_STORE_ID!,
      apiKey: process.env.DEV_API_KEY!,
      environment: Environment.Staging
    },
    staging: {
      name: "Staging",
      storeId: process.env.STAGING_STORE_ID!,
      apiKey: process.env.STAGING_API_KEY!,
      environment: Environment.Staging
    },
    production: {
      name: "Production",
      storeId: process.env.PROD_STORE_ID!,
      apiKey: process.env.PROD_API_KEY!,
      environment: Environment.Production
    }
  };
  
  createSDK(envName: string, overrides?: Partial<StorefrontSDKOptions>): StorefrontSDK {
    const env = this.environments[envName];
    if (!env) throw new Error(`Unknown environment: ${envName}`);
    
    return createStorefront({
      storeId: env.storeId,
      environment: env.environment,
      apiKey: env.apiKey,
      baseUrl: env.baseUrl,
      
      // Environment-specific defaults
      timeout: envName === "development" ? 30000 : 10000,
      debug: envName === "development",
      
      tokenStorage: new CookieTokenStorage({
        prefix: `${envName}_`,
        secure: envName === "production"
      }),
      
      // Apply overrides
      ...overrides
    });
  }
}

// Usage
const factory = new SDKConfigFactory();
const sdk = factory.createSDK("production", {
  timeout: 15000,
  debug: true // Override for debugging production issues
});
```

## Best Practices

### ✅ Configuration Recommendations

<CardGroup cols={2}>
  <Card title="Environment Variables" icon="shield">
    Always use environment variables for sensitive configuration like API keys and store IDs
  </Card>

  <Card title="Secure Defaults" icon="lock">
    Use secure cookie settings in production with appropriate SameSite and Secure flags
  </Card>

  <Card title="Timeout Tuning" icon="stopwatch">
    Set custom timeouts for your environment - longer for development, shorter for production
  </Card>

  <Card title="Debug Control" icon="bug">
    Enable debugging in development but disable in production for performance and security
  </Card>
</CardGroup>

### Security Checklist

<Steps>
  <Step title="Use Environment Variables">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // ✅ GOOD
    const sdk = createStorefront({
      storeId: process.env.NEXT_PUBLIC_STORE_ID!,
      apiKey: process.env.NEXT_PUBLIC_API_KEY!,
      // ...
    });

    // ❌ BAD
    const sdk = createStorefront({
      storeId: "hardcoded-store-id",
      apiKey: "sk_live_hardcoded_key",
      // ...
    });
    ```
  </Step>

  <Step title="Secure Cookie Configuration">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // ✅ GOOD
    const tokenStorage = new CookieTokenStorage({
      secure: true,        // HTTPS only
      sameSite: "Lax",     // CSRF protection
      httpOnly: false      // Required for client access
    });

    // ❌ BAD
    const tokenStorage = new CookieTokenStorage({
      secure: false,       // Allows HTTP transmission
      sameSite: "None"     // Vulnerable to CSRF
    });
    ```
  </Step>

  <Step title="Environment-Specific Settings">
    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // ✅ GOOD
    const isProduction = process.env.NODE_ENV === "production";

    const sdk = createStorefront({
      environment: isProduction ? Environment.Production : Environment.Staging,
      debug: !isProduction,
      timeout: isProduction ? 10000 : 30000,
      // ...
    });
    ```
  </Step>
</Steps>

<Warning>
  **Never commit API keys or sensitive configuration to version control.** Use environment variables and `.env` files that are excluded from your repository.
</Warning>

<Check>
  **Configuration Summary**: The SDK's flexible configuration system allows you to adapt to any environment while maintaining security and performance. Use automatic token management with appropriate storage for your platform, and always follow security best practices for production deployments.
</Check>
