How OpenSEO Uses the DataForSEO Keywords Data API for Keyword Research
OpenSEO integrates the DataForSEO Labs Keywords Data API through a layered architecture that handles request construction, credit-based billing, location normalization, and granular error handling to deliver reliable keyword research with transparent cost tracking.
OpenSEO leverages the DataForSEO Labs Keywords Data API to power its keyword research capabilities, wrapping the third-party service in a robust TypeScript client that manages authentication, request validation, and usage-based billing. The implementation spans multiple modules across the codebase, from low-level HTTP client configuration in src/server/lib/dataforseo/client.ts to high-level workflow orchestration in src/server/workflows/RankCheckWorkflow.ts.
Request Building and API Client Configuration
The foundation of OpenSEO’s keyword research integration resides in src/server/lib/dataforseo/client.ts. This module exports the createDataforseoClient factory function, which instantiates a configured HTTP client for interacting with DataForSEO Labs endpoints.
The client handles authentication by encoding the API credentials using base‑64 email:password format and injecting the required HTTP headers. It also constructs the JSON payload that DataForSEO expects, including parameters for keyword, language_code, and location_code. For example, when fetching related keywords, the client posts to the endpoint path ["v3","dataforseo_labs","google","related_keywords","live"] with a payload structure matching the API’s strict schema requirements.
Endpoint Mapping and Credit Feature Assignment
Before any HTTP request executes, OpenSEO determines the billing implications through src/shared/billing-credit-features.ts. This module maintains an endpoint mapper that associates each DataForSEO API path with an internal credit feature identifier.
When the client targets the related keywords or keyword suggestions endpoints, the mapper assigns the keyword_research credit feature. This mapping enables automatic usage tracking, ensuring that every API call deducts the appropriate number of credits from the user’s balance before the request completes.
Location and Language Normalization
Accurate localization requires translating user-friendly inputs into DataForSEO’s standardized codes. The src/shared/keyword-locations.ts module validates that supplied domain/locale combinations are supported by DataForSEO Labs and rejects malformed hosts or IP addresses before network requests occur.
This layer translates UI-selected location names into the location_code and language_code parameters required by the DataForSEO Keywords Data API, ensuring that search volume and keyword difficulty metrics reflect the correct geographic and linguistic markets.
Workflow Execution and Billing Integration
The src/server/workflows/RankCheckWorkflow.ts orchestrates the end-to-end keyword research process. This workflow executes the HTTP request through the DataForSEO client, captures the raw response, and handles charged errors—failures where DataForSEO still bills the request due to validation issues like "Invalid Field".
Upon receiving a response (successful or charged-error), the workflow records the cost against the user’s credit balance and feeds the processed keyword data back to the UI or MCP client. The same workflow handles both rank-checking and keyword research operations, providing a unified interface for DataForSEO Labs data retrieval.
Error handling distinguishes between standard failures and DataforseoChargedTaskError instances. When the API returns a charged error, the error wrapper preserves the exact USD cost while propagating a user-friendly message to the front-end, preventing hidden over-usage. Unit tests in src/server/lib/dataforseo/client.test.ts verify this error-wrapped logic and credit accounting accuracy.
Research Scope and Filter Management
OpenSEO supports granular research scopes—domain, subdomain, subfolder, and exact URL—which consume varying numbers of DataForSEO filter slots. The src/shared/researchScope.ts module defines RESEARCH_SCOPE_FILTER_SLOTS to track these constraints, ensuring that complex queries (such as subfolder-level research) do not exceed the API’s eight-filter limit while maintaining accurate credit cost calculations for intensive queries.
Implementation Example
The following TypeScript example demonstrates fetching related keywords while handling charged errors:
import { createDataforseoClient } from "@/server/lib/dataforseo/client";
import { billingCustomer } from "@/server/lib/billing";
async function fetchRelatedKeywords(seed: string) {
const client = createDataforseoClient(billingCustomer);
// Construct payload for DataForSEO Labs API
const payload = {
keyword: seed,
language_code: "en",
location_code: "us",
};
// Hits: v3/dataforseo_labs/google/related_keywords/live
const result = await client.keywords.relatedKeywords(payload);
return result; // Array of {keyword, search_volume, difficulty, intent, ...}
}
// Usage with error handling
try {
const data = await fetchRelatedKeywords("open source seo");
console.log("Related keywords:", data);
} catch (e) {
if (e instanceof DataforseoChargedTaskError) {
// Error was billed—surface friendly message without hiding cost
console.warn("DataForSEO error (billed):", e.message);
} else {
console.error("Unexpected error:", e);
}
}
Summary
- Authentication and Request Building: The
createDataforseoClientfunction insrc/server/lib/dataforseo/client.tshandles base‑64 credential encoding and JSON payload construction for DataForSEO Labs endpoints. - Credit Tracking:
src/shared/billing-credit-features.tsmaps API paths to internal credit features likekeyword_research, enabling automatic per-user usage tracking. - Localization:
src/shared/keyword-locations.tsvalidates and translates UI locations into DataForSEOlocation_codeandlanguage_codeparameters. - Workflow Integration:
src/server/workflows/RankCheckWorkflow.tsexecutes requests, processes charged errors throughDataforseoChargedTaskError, and updates user credit balances. - Scope Management:
src/shared/researchScope.tsenforces filter slot limits based on research scope (domain, subfolder, etc.) to prevent API constraint violations.
Frequently Asked Questions
How does OpenSEO authenticate with the DataForSEO Keywords Data API?
OpenSEO authenticates using the createDataforseoClient function in src/server/lib/dataforseo/client.ts, which encodes the API key as a base‑64 email:password string and injects it into the Authorization header. This approach ensures secure credential transmission for every request to DataForSEO Labs endpoints.
What happens to my credits if a keyword research request fails?
If DataForSEO returns a charged error (such as "Invalid Field"), OpenSEO still deducts the appropriate credits from your balance. The platform wraps these errors in DataforseoChargedTaskError, preserving the exact USD cost while displaying a user-friendly message, ensuring transparent billing even for failed requests.
How does OpenSEO handle different countries and languages for keyword research?
The system uses src/shared/keyword-locations.ts to validate user-selected domains and locales, rejecting unsupported inputs or malformed hosts before sending requests. It then translates the selected location into DataForSEO’s standardized location_code and language_code parameters to ensure metrics reflect the correct market.
Can I research keywords for specific subfolders or URLs rather than entire domains?
Yes. OpenSEO supports multiple research scopes—including domain, subdomain, subfolder, and exact URL—managed through src/shared/researchScope.ts. The system tracks filter slot consumption via RESEARCH_SCOPE_FILTER_SLOTS to ensure complex subfolder queries respect DataForSEO’s eight-filter limit while calculating appropriate credit costs for intensive searches.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →