> ## Documentation Index
> Fetch the complete documentation index at: https://betterdatainc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom Backends

> Connect any data source or private API to the gateway

If you aren't using Shopify or Square, or if you need to pull data from multiple sources, you can easily implement a Custom Backend.

## Implementation

To create a custom backend, you simply need to implement one or more of the core interfaces: `ProductBackend`, `CartBackend`, or `OrderBackend`.

### Example: MySQL/Postgres Backend

```typescript theme={null}
import { ProductBackend, Product } from '@commercegateway/commerce-gateway';

class MyDatabaseBackend implements ProductBackend {
  async searchProducts(query: string): Promise<ProductSearchResult> {
    const results = await db.products.findMany({
      where: { name: { contains: query } }
    });
    
    return {
      products: results.map(this.mapToProduct),
      total: results.length,
      hasMore: false,
    };
  }

  async getProductDetails(id: string): Promise<Product | null> {
    const product = await db.products.findUnique({ where: { id } });
    return product ? this.mapToProduct(product) : null;
  }

  private mapToProduct(raw: any): Product {
    return {
      id: raw.id,
      name: raw.title,
      price: { amount: raw.price, currency: 'USD' },
      // ...
    };
  }
}
```

## Using your Backend

Once implemented, pass your custom class to the gateway:

```typescript theme={null}
const gateway = new LLMGateway({
  backends: {
    products: new MyDatabaseBackend(),
  }
});
```

## Hybrid Backends

You can also mix and match. For example, use **Shopify** for product data but a **Custom API** for complex loyalty points or custom fulfillment rules.

```typescript theme={null}
const gateway = new LLMGateway({
  backends: {
    products: new ShopifyBackend(...),
    cart: new MyCustomLoyaltyCartBackend(...),
  }
});
```

## Best Practices

* **Timeout Management**: Ensure your custom backend methods have sensible timeouts to prevent blocking the LLM interaction.
* **Validation**: Use Zod within your backend to validate data coming from your internal services.
* **Error Mapping**: Map your internal database errors to the gateway's [Standard Error Types](/reference/error-handling).
