# DataForSEO API Client Structure in OpenSEO: Architecture and Implementation Guide

> Explore the DataForSEO API client structure in OpenSEO. Understand its three-layer architecture for authentication transport, response normalization, and domain-specific modules for effective SEO operations.

- Repository: [Every App/open-seo](https://github.com/every-app/open-seo)
- Tags: architecture
- Published: 2026-07-23

---

**The DataForSEO API client in OpenSEO follows a modular three-layer architecture consisting of authentication transport in [`core.ts`](https://github.com/every-app/open-seo/blob/main/core.ts), response normalization via [`envelope.ts`](https://github.com/every-app/open-seo/blob/main/envelope.ts), and domain-specific modules for SERP, backlinks, and AI optimization located under `src/server/lib/dataforseo/`.**

The OpenSEO application interfaces with the DataForSEO API through a strongly-typed TypeScript client. This structure separates HTTP transport concerns from endpoint-specific business logic while providing comprehensive error classification and Zod validation for all API responses.

## Core Client Architecture

The foundation of the DataForSEO client resides in `src/server/lib/dataforseo/` and consists of three architectural layers that handle authentication, error normalization, and endpoint abstraction.

### Transport and Authentication ([`core.ts`](https://github.com/every-app/open-seo/blob/main/core.ts))

The **authentication layer** is implemented in [`src/server/lib/dataforseo/core.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/core.ts). This file exports `createAuthenticatedFetch`, a factory function that constructs an HTTP client pre-configured with DataForSEO credentials. All domain-specific modules consume this wrapper to ensure consistent header injection and base URL management.

### Response Normalization ([`envelope.ts`](https://github.com/every-app/open-seo/blob/main/envelope.ts))

The **envelope layer** in [`src/server/lib/dataforseo/envelope.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/envelope.ts) processes raw DataForSEO responses. It defines `DataforseoChargedTaskError`, a specialized error class thrown when the API returns non-2xx status codes. This normalization ensures that downstream code receives typed errors rather than raw HTTP responses, enabling precise handling of billing and feature-access failures.

## Error Classification System

Beyond basic HTTP error mapping, the client implements sophisticated **billing and access control classification** in [`src/server/lib/dataforseo/dataforseoBillingClassification.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/dataforseoBillingClassification.ts). This module exports `createDataforseoBillingClassifier`, which maps specific DataForSEO status codes to internal error types.

This classification allows server functions to differentiate between transient failures, exhausted account balances, and disabled features without parsing raw API messages.

## Domain-Specific API Modules

The client exposes DataForSEO functionality through focused modules that wrap specific endpoint categories. Each module exports a factory function that accepts an optional error classifier, maintaining clean separation between transport logic and business rules.

### SERP Module ([`serp.ts`](https://github.com/every-app/open-seo/blob/main/serp.ts))

The **SERP module** in [`src/server/lib/dataforseo/serp.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/serp.ts) provides access to search engine results page data. It exports `serpApi`, which implements methods like `keywordsLive` for real-time keyword data and task-queue operations for asynchronous processing.

Higher-level server functions such as [`src/serverFunctions/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/keywords.ts) and [`src/serverFunctions/rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/rank-tracking.ts) import this module to execute keyword research and rank monitoring workflows.

```typescript
import { serpApi } from '@/server/lib/dataforseo/serp';
import { createDataforseoBillingClassifier } from '@/server/lib/dataforseo/dataforseoBillingClassification';

const classifySerpError = createDataforseoBillingClassifier({});

async function fetchKeywordVolume(keyword: string, locationCode: string) {
  const api = serpApi(classifySerpError);
  const response = await api.keywordsLive([
    {
      keywords: [keyword],
      location_code: Number(locationCode),
    },
  ]);
  return response[0];
}

```

### Backlinks Module ([`backlinks.ts`](https://github.com/every-app/open-seo/blob/main/backlinks.ts))

The **backlinks module** in [`src/server/lib/dataforseo/backlinks.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/backlinks.ts) exports `backlinksApi`, providing methods for `backlinksLive`, `summaryLive`, and `historyLive` endpoints. The [`src/serverFunctions/domain.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/domain.ts) file utilizes this module alongside the SERP client to construct comprehensive domain overview reports.

```typescript
import { backlinksApi } from '@/server/lib/dataforseo/backlinks';
import { createDataforseoBillingClassifier } from '@/server/lib/dataforseo/dataforseoBillingClassification';

const classifyBacklinksError = createDataforseoBillingClassifier({});

async function getBacklinksProfile(domain: string) {
  const api = backlinksApi(classifyBacklinksError);
  const summary = await api.summaryLive([{ target: domain }]);
  const rows = await api.backlinksLive([
    {
      target: domain,
      limit: 30,
      offset: 0,
    },
  ]);
  return { summary: summary[0], rows };
}

```

### AI Optimization Module ([`ai.ts`](https://github.com/every-app/open-seo/blob/main/ai.ts))

The **AI module** in [`src/server/lib/dataforseo/ai.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/ai.ts) wraps DataForSEO's AI optimization endpoints through the `aiOptimizationApi` factory. This module handles content optimization suggestions and keyword recommendations, utilizing type definitions from [`dataforseoLlmSchemas.ts`](https://github.com/every-app/open-seo/blob/main/dataforseoLlmSchemas.ts).

```typescript
import { aiOptimizationApi } from '@/server/lib/dataforseo/ai';
import { createDataforseoBillingClassifier } from '@/server/lib/dataforseo/dataforseoBillingClassification';

const classifyAiError = createDataforseoBillingClassifier({});

async function getAiOptimizationSuggestions(url: string) {
  const api = aiOptimizationApi(classifyAiError);
  const result = await api.optimizeLive([{ target: url }]);
  return result[0];
}

```

## Type Safety and Schema Validation

Runtime type safety is enforced through **Zod schemas** located in auxiliary files such as [`src/server/lib/dataforseo/dataforseoLlmSchemas.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/dataforseoLlmSchemas.ts) and [`src/server/lib/dataforseo/dataforseoLighthousePayload.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/dataforseoLighthousePayload.ts). These schemas validate DataForSEO responses before they reach application logic, ensuring that TypeScript types remain synchronized with the actual API contract.

The validation occurs within the domain-specific modules immediately after the envelope processing, creating a closed pipeline: Raw Response → Authentication Check → Error Classification → Zod Validation → Typed Return.

## Integration with Server Functions

The modular client design enables clean consumption patterns in higher-level server functions:

- **[`src/serverFunctions/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/keywords.ts)** – Orchestrates keyword research by calling the SERP module's live endpoints
- **[`src/serverFunctions/domain.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/domain.ts)** – Combines SERP and Backlinks modules to generate domain authority metrics and backlink profiles
- **[`src/serverFunctions/rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/rank-tracking.ts)** – Utilizes the SERP task-queue client with custom polling logic for position tracking

This architecture ensures that transport details remain encapsulated within `src/server/lib/dataforseo/` while business logic in `src/serverFunctions/` operates exclusively with typed, validated data structures.

## Summary

- **Transport Layer**: [`core.ts`](https://github.com/every-app/open-seo/blob/main/core.ts) provides authenticated HTTP via `createAuthenticatedFetch` used by all modules
- **Error Handling**: [`envelope.ts`](https://github.com/every-app/open-seo/blob/main/envelope.ts) defines `DataforseoChargedTaskError` while [`dataforseoBillingClassification.ts`](https://github.com/every-app/open-seo/blob/main/dataforseoBillingClassification.ts) enables granular error mapping
- **Domain Modules**: [`serp.ts`](https://github.com/every-app/open-seo/blob/main/serp.ts), [`backlinks.ts`](https://github.com/every-app/open-seo/blob/main/backlinks.ts), and [`ai.ts`](https://github.com/every-app/open-seo/blob/main/ai.ts) export factory functions (`serpApi`, `backlinksApi`, `aiOptimizationApi`) for specific DataForSEO endpoints
- **Validation**: Zod schemas in [`dataforseoLlmSchemas.ts`](https://github.com/every-app/open-seo/blob/main/dataforseoLlmSchemas.ts) and related files ensure runtime type safety
- **Consumption**: Server functions in `src/serverFunctions/` import these modules to implement keyword research, domain analysis, and rank tracking features

## Frequently Asked Questions

### How does the DataForSEO client handle authentication?

Authentication is centralized in [`src/server/lib/dataforseo/core.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/core.ts) through the `createAuthenticatedFetch` function. This factory injects the DataForSEO token into request headers and manages the base URL, ensuring all domain-specific modules (SERP, backlinks, AI) use a consistently authenticated transport layer without duplicating credential logic.

### What error handling mechanisms are implemented in the OpenSEO DataForSEO client?

The client implements a two-stage error handling system. First, [`src/server/lib/dataforseo/envelope.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/envelope.ts) normalizes all responses and throws `DataforseoChargedTaskError` for non-2xx statuses. Second, [`src/server/lib/dataforseo/dataforseoBillingClassification.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/dataforseoBillingClassification.ts) provides `createDataforseoBillingClassifier`, which maps specific DataForSEO status codes (such as balance exhaustion or feature restrictions) to typed internal errors that server functions can catch and handle appropriately.

### How is type safety ensured when interacting with the DataForSEO API?

Type safety is maintained through Zod schemas defined in files like [`src/server/lib/dataforseo/dataforseoLlmSchemas.ts`](https://github.com/every-app/open-seo/blob/main/src/server/lib/dataforseo/dataforseoLlmSchemas.ts) and [`dataforseoLighthousePayload.ts`](https://github.com/every-app/open-seo/blob/main/dataforseoLighthousePayload.ts). These schemas validate API responses at runtime before they are returned to callers, guaranteeing that the TypeScript types match the actual DataForSEO payload structure and preventing propagation of malformed data into the application.

### Which server functions utilize the DataForSEO client modules?

The primary consumers are located in `src/serverFunctions/`: [`keywords.ts`](https://github.com/every-app/open-seo/blob/main/keywords.ts) uses the SERP module for keyword research, [`domain.ts`](https://github.com/every-app/open-seo/blob/main/domain.ts) combines SERP and Backlinks modules for domain overview analysis, and [`rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/rank-tracking.ts) leverages the SERP task-queue client for asynchronous rank monitoring workflows.