npm package: @power-seo/integrations
Description: Third-party SEO tool API clients for Semrush and Ahrefs with shared HTTP client
Author: CyberCraft Bangladesh
Latest version: 1.0.15

# @power-seo/integrations

![integrations banner](https://raw.githubusercontent.com/CyberCraftBD/power-seo/main/image/integrations/banner.svg)

Query keyword data, domain overviews, backlinks, and keyword difficulty from Semrush and Ahrefs APIs with a shared HTTP client that handles rate limiting and pagination automatically.

[![npm version](https://img.shields.io/npm/v/@power-seo/integrations)](https://www.npmjs.com/package/@power-seo/integrations)
[![npm downloads](https://img.shields.io/npm/dm/@power-seo/integrations)](https://www.npmjs.com/package/@power-seo/integrations)
[![Socket](https://socket.dev/api/badge/npm/package/@power-seo/integrations)](https://socket.dev/npm/package/@power-seo/integrations)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
[![tree-shakeable](https://img.shields.io/badge/tree--shakeable-yes-brightgreen)](https://bundlephobia.com/package/@power-seo/integrations)

`@power-seo/integrations` wraps the Semrush and Ahrefs REST APIs with a consistent TypeScript interface. Both clients are built on a shared `createHttpClient()` base that enforces configurable rate limits (requests per window), handles pagination automatically, and normalizes errors into `IntegrationApiError` with status codes and messages. Import only the client you need — tree-shaking ensures unused API code never ends up in your bundle.

> **Zero runtime dependencies beyond `fetch`** — runs in Node.js 18+, Deno, Bun, and modern edge runtimes.
>
> ⚠️ **Network Access** — This package makes HTTPS requests to Semrush and Ahrefs APIs. Network access is functionally required and intentional. All requests use your API credentials and are sent only to the configured service endpoints.

---

## Why @power-seo/integrations?

|                  | Without                   | With                                                            |
| ---------------- | ------------------------- | --------------------------------------------------------------- |
| Semrush API      | ❌ Write raw HTTP client  | ✅ Typed client with auto-pagination                            |
| Ahrefs API       | ❌ Manual SDK setup       | ✅ Typed client with rate limiting                              |
| Rate limiting    | ❌ Manual throttle        | ✅ Built-in configurable window rate limiter                    |
| Pagination       | ❌ Manual offset tracking | ✅ Automatic — receive a flat result array                      |
| Error handling   | ❌ Raw HTTP errors        | ✅ `IntegrationApiError` with `status`, `provider`, `retryable` |
| TypeScript types | ❌ `any` everywhere       | ✅ Full type coverage for all endpoints                         |
| Bundle size      | ❌ Full SDK in bundle     | ✅ Tree-shakeable — import only what you use                    |

![Integrations Comparison](https://raw.githubusercontent.com/CyberCraftBD/power-seo/main/image/integrations/comparison.svg)

<p align="left">
  <a href="https://www.buymeacoffee.com/ccbd.dev" target="_blank">
    <img src="https://img.buymeacoffee.com/button-api/?text=Buy%20me%20a%20coffee&emoji=&slug=ccbd.dev&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff" />
  </a>
</p>

---

## Features

- **Semrush API client** — domain overview (traffic, organic/paid keywords, backlinks), keyword data (volume, CPC, competition), backlink profile, keyword difficulty, and related keyword suggestions
- **Ahrefs API client** — site overview (Domain Rating, organic traffic), organic keywords with positions, backlink data with anchor text, keyword difficulty, and referring domain list
- **Shared HTTP client** — `createHttpClient()` provides configurable rate limiting (max requests per time window), automatic retry on 429, and JSON response parsing
- **Auto-pagination** — both clients handle multi-page results automatically; callers receive a flat array without manual offset tracking
- **Full TypeScript types** — every request parameter and response field is typed; no `any` in your code
- **Consistent error handling** — `IntegrationApiError` with `status`, `provider`, `message`, and `retryable` flag from both APIs
- **Tree-shakeable** — `createSemrushClient` and `createAhrefsClient` are separate exports; import only what you use

![SEO Research UI](https://raw.githubusercontent.com/CyberCraftBD/power-seo/main/image/integrations/seo-research-ui.svg)

---

## Comparison

| Feature                   | @power-seo/integrations | semrush-sdk | ahrefs-client | Custom fetch |
| ------------------------- | :---------------------: | :---------: | :-----------: | :----------: |
| Semrush API client        |           ✅            |     ✅      |      ❌       |    Manual    |
| Ahrefs API client         |           ✅            |     ❌      |    Partial    |    Manual    |
| Rate limiting             |           ✅            |   Partial   |      ❌       |    Manual    |
| Auto-pagination           |           ✅            |     ❌      |      ❌       |    Manual    |
| Shared HTTP client        |           ✅            |     ❌      |      ❌       |      —       |
| Consistent error handling |           ✅            |   Partial   |      ❌       |    Manual    |
| TypeScript-first          |           ✅            |     ❌      |      ❌       |      —       |
| Tree-shakeable            |           ✅            |     ❌      |      ❌       |      —       |

![Rate Limit Accuracy](https://raw.githubusercontent.com/CyberCraftBD/power-seo/main/image/integrations/rate-limit-accuracy.svg)

---

## Installation

```bash
npm install @power-seo/integrations
```

```bash
yarn add @power-seo/integrations
```

```bash
pnpm add @power-seo/integrations
```

---

## Quick Start

```ts
import { createSemrushClient, createAhrefsClient } from '@power-seo/integrations';

// Semrush
const semrush = createSemrushClient({ apiKey: process.env.SEMRUSH_API_KEY! });
const overview = await semrush.getDomainOverview({ domain: 'example.com' });
console.log(overview.organicTraffic); // 12_400
console.log(overview.organicKeywords); // 834

// Ahrefs
const ahrefs = createAhrefsClient({ apiKey: process.env.AHREFS_API_KEY! });
const site = await ahrefs.getSiteOverview({ target: 'example.com' });
console.log(site.domainRating); // 47
console.log(site.organicTraffic); // 9_800
```

![Unification Benefit](https://raw.githubusercontent.com/CyberCraftBD/power-seo/main/image/integrations/unification-benefit.svg)

---

## Usage

### Semrush Client

```ts
import { createSemrushClient } from '@power-seo/integrations';
import type { SemrushDomainOverview, SemrushKeywordData } from '@power-seo/integrations';

const semrush = createSemrushClient(
  process.env.SEMRUSH_API_KEY!,
  { rateLimitPerMinute: 10, maxRetries: 3 }, // optional
);

// Domain overview — traffic, keywords, backlinks
const overview: SemrushDomainOverview = await semrush.getDomainOverview('example.com', 'us');
// { domain, organicTraffic, paidTraffic, organicKeywords, paidKeywords, backlinks, authorityScore }

// Organic keywords
const keywords = await semrush.getOrganicKeywords('example.com', { limit: 100, offset: 0 });
// { data: SemrushKeywordData[], total, offset, limit, hasMore }

// Backlinks
const backlinks = await semrush.getBacklinks('example.com', { limit: 100, offset: 0 });
// { data: SemrushBacklinkData[], total, offset, limit, hasMore }

// Keyword difficulty
const difficulty = await semrush.getKeywordDifficulty(['react seo'], 'us');
// [{ keyword, difficulty, searchVolume, cpc, competition, results }]

// Related keywords
const related = await semrush.getRelatedKeywords('react seo', 'us');
// [{ keyword, searchVolume, cpc, competition, results, relatedTo }]
```

### Ahrefs Client

```ts
import { createAhrefsClient } from '@power-seo/integrations';
import type { AhrefsSiteOverview, AhrefsOrganicKeyword } from '@power-seo/integrations';

const ahrefs = createAhrefsClient(
  process.env.AHREFS_API_TOKEN!,
  { rateLimitPerMinute: 5, maxRetries: 3 }, // optional
);

// Site overview — DR, organic traffic, backlinks
const overview: AhrefsSiteOverview = await ahrefs.getSiteOverview('example.com');
// { domain, domainRating, urlRating, organicTraffic, organicKeywords, backlinks, referringDomains, trafficValue }

// Organic keywords with positions
const keywords = await ahrefs.getOrganicKeywords('example.com', { limit: 200, offset: 0 });
// { data: AhrefsOrganicKeyword[], total, offset, limit, hasMore }

// Backlinks with anchor text
const backlinks = await ahrefs.getBacklinks('example.com', { limit: 100, offset: 0 });
// { data: AhrefsBacklink[], total, offset, limit, hasMore }

// Keyword difficulty
const kd = await ahrefs.getKeywordDifficulty(['react seo']);
// [{ keyword, difficulty, searchVolume, cpc, clicks, globalVolume }]

// Referring domains
const domains = await ahrefs.getReferringDomains('example.com', { limit: 50, offset: 0 });
// { data: AhrefsReferringDomain[], total, offset, limit, hasMore }
```

### Shared HTTP Client

Use the underlying HTTP client directly to call any REST API with rate limiting and pagination:

```ts
import { createHttpClient } from '@power-seo/integrations';

const http = createHttpClient({
  baseUrl: 'https://api.example.com',
  auth: { type: 'bearer', token },
  rateLimitPerMinute: 60, // max requests per minute
  maxRetries: 3,
  timeoutMs: 30_000,
});

const data = await http.get<MyResponseType>('/endpoint', { query: 'param' });
```

### Error Handling

Both clients throw `IntegrationApiError` for non-2xx responses:

```ts
import { createSemrushClient, IntegrationApiError } from '@power-seo/integrations';

const semrush = createSemrushClient({ apiKey: 'your-key' });

try {
  const data = await semrush.getDomainOverview('example.com');
} catch (err) {
  if (err instanceof IntegrationApiError) {
    console.error(`API error ${err.status}: ${err.message}`);
    console.error('Provider:', err.provider);
    console.error('Retryable:', err.retryable);
  } else {
    throw err;
  }
}
```

---

## API Reference

### Semrush

```ts
function createSemrushClient(
  apiKey: string,
  config?: Partial<Omit<HttpClientConfig, 'baseUrl' | 'auth'>>,
): SemrushClient;
```

#### `SemrushClient` methods

| Method                 | Parameters                | Returns                                  | Description                          |
| ---------------------- | ------------------------- | ---------------------------------------- | ------------------------------------ |
| `getDomainOverview`    | `(domain, database?)`     | `SemrushDomainOverview`                  | Traffic, keywords, backlinks summary |
| `getOrganicKeywords`   | `(domain, options?)`      | `PaginatedResponse<SemrushKeywordData>`  | Keywords with rankings               |
| `getBacklinks`         | `(domain, options?)`      | `PaginatedResponse<SemrushBacklinkData>` | Backlinks with source/target URLs    |
| `getKeywordDifficulty` | `(keywords[], database?)` | `SemrushKeywordDifficulty[]`             | KD scores with volume/CPC            |
| `getRelatedKeywords`   | `(keyword, database?)`    | `SemrushRelatedKeyword[]`                | Related keyword suggestions          |

### Ahrefs

```ts
function createAhrefsClient(
  apiToken: string,
  config?: Partial<Omit<HttpClientConfig, 'baseUrl' | 'auth'>>,
): AhrefsClient;
```

#### `AhrefsClient` methods

| Method                 | Parameters           | Returns                                    | Description                     |
| ---------------------- | -------------------- | ------------------------------------------ | ------------------------------- |
| `getSiteOverview`      | `(domain)`           | `AhrefsSiteOverview`                       | DR, organic traffic, backlinks  |
| `getOrganicKeywords`   | `(domain, options?)` | `PaginatedResponse<AhrefsOrganicKeyword>`  | Ranking keywords with positions |
| `getBacklinks`         | `(domain, options?)` | `PaginatedResponse<AhrefsBacklink>`        | Backlinks with anchor text      |
| `getKeywordDifficulty` | `(keywords[])`       | `AhrefsKeywordDifficulty[]`                | KD scores with volume/CPC       |
| `getReferringDomains`  | `(domain, options?)` | `PaginatedResponse<AhrefsReferringDomain>` | Referring domains by DR         |

### Shared

```ts
function createHttpClient(config: HttpClientConfig): HttpClient;
```

#### `HttpClientConfig`

| Prop                 | Type           | Default | Description                                  |
| -------------------- | -------------- | ------- | -------------------------------------------- |
| `baseUrl`            | `string`       | —       | Base URL for all requests                    |
| `auth`               | `AuthStrategy` | —       | Authentication: bearer token or query        |
| `rateLimitPerMinute` | `number`       | —       | Optional: max requests per minute            |
| `maxRetries`         | `number`       | —       | Optional: retry failed requests (default: 3) |
| `timeoutMs`          | `number`       | —       | Optional: request timeout in milliseconds    |

**AuthStrategy** is one of:

- `{ type: 'bearer', token: string }` — Authorization header
- `{ type: 'query', paramName: string, value: string }` — Query parameter auth

### Types

```ts
import type {
  HttpClientConfig,
  HttpClient,
  PaginatedResponse,
  SemrushConfig,
  SemrushDomainOverview,
  SemrushKeywordData,
  SemrushBacklinkData,
  SemrushRelatedKeyword,
  SemrushClient,
  AhrefsConfig,
  AhrefsSiteOverview,
  AhrefsOrganicKeyword,
  AhrefsBacklink,
  AhrefsReferringDomain,
  AhrefsClient,
} from '@power-seo/integrations';
```

---

## Use Cases

- **Keyword research pipelines** — pull volume and difficulty from Semrush to prioritize content creation
- **Backlink monitoring** — automate periodic Ahrefs backlink snapshots for link building tracking
- **Competitor analysis** — use domain overview data to compare your metrics against competitors
- **Content brief generation** — combine keyword difficulty and volume to prioritize blog topics
- **SEO reporting dashboards** — pull live Semrush/Ahrefs data into internal analytics tools built with `@power-seo/analytics`

---

## Architecture Overview

- **Pure TypeScript** — no compiled binary, no native modules
- **Minimal runtime dependencies** — only native `fetch` (available in Node 18+, Deno, Bun, and all Edge runtimes)
- **Framework-agnostic** — works in Next.js API routes, Remix loaders, Express, Cloudflare Workers
- **SSR compatible** — safe for server-side use; no browser-specific APIs
- **Edge runtime safe** — uses only `fetch`; runs in Cloudflare Workers, Vercel Edge, Deno
- **Tree-shakeable** — `createSemrushClient` and `createAhrefsClient` are separate named exports
- **Dual ESM + CJS** — ships both formats via tsup for any bundler or `require()` usage

---

## Supply Chain Security

- No install scripts (`postinstall`, `preinstall`)
- No runtime network access beyond explicit API calls you initiate
- No `eval` or dynamic code execution
- CI-signed builds — all releases published via verified `github.com/CyberCraftBD/power-seo` workflow
- Safe for SSR, Edge, and server environments

---

## The [@power-seo](https://www.npmjs.com/org/power-seo) Ecosystem

All 17 packages are independently installable — use only what you need.

| Package                                                                                    | Install                             | Description                                                             |
| ------------------------------------------------------------------------------------------ | ----------------------------------- | ----------------------------------------------------------------------- |
| [`@power-seo/core`](https://www.npmjs.com/package/@power-seo/core)                         | `npm i @power-seo/core`             | Framework-agnostic utilities, types, validators, and constants          |
| [`@power-seo/react`](https://www.npmjs.com/package/@power-seo/react)                       | `npm i @power-seo/react`            | React SEO components — meta, Open Graph, Twitter Card, breadcrumbs      |
| [`@power-seo/meta`](https://www.npmjs.com/package/@power-seo/meta)                         | `npm i @power-seo/meta`             | SSR meta helpers for Next.js App Router, Remix v2, and generic SSR      |
| [`@power-seo/schema`](https://www.npmjs.com/package/@power-seo/schema)                     | `npm i @power-seo/schema`           | Type-safe JSON-LD structured data — 23 builders + 22 React components   |
| [`@power-seo/content-analysis`](https://www.npmjs.com/package/@power-seo/content-analysis) | `npm i @power-seo/content-analysis` | Yoast-style SEO content scoring engine with React components            |
| [`@power-seo/readability`](https://www.npmjs.com/package/@power-seo/readability)           | `npm i @power-seo/readability`      | Readability scoring — Flesch-Kincaid, Gunning Fog, Coleman-Liau, ARI    |
| [`@power-seo/preview`](https://www.npmjs.com/package/@power-seo/preview)                   | `npm i @power-seo/preview`          | SERP, Open Graph, and Twitter/X Card preview generators                 |
| [`@power-seo/sitemap`](https://www.npmjs.com/package/@power-seo/sitemap)                   | `npm i @power-seo/sitemap`          | XML sitemap generation, streaming, index splitting, and validation      |
| [`@power-seo/redirects`](https://www.npmjs.com/package/@power-seo/redirects)               | `npm i @power-seo/redirects`        | Redirect engine with Next.js, Remix, and Express adapters               |
| [`@power-seo/links`](https://www.npmjs.com/package/@power-seo/links)                       | `npm i @power-seo/links`            | Link graph analysis — orphan detection, suggestions, equity scoring     |
| [`@power-seo/audit`](https://www.npmjs.com/package/@power-seo/audit)                       | `npm i @power-seo/audit`            | Full SEO audit engine — meta, content, structure, performance rules     |
| [`@power-seo/images`](https://www.npmjs.com/package/@power-seo/images)                     | `npm i @power-seo/images`           | Image SEO — alt text, lazy loading, format analysis, image sitemaps     |
| [`@power-seo/ai`](https://www.npmjs.com/package/@power-seo/ai)                             | `npm i @power-seo/ai`               | LLM-agnostic AI prompt templates and parsers for SEO tasks              |
| [`@power-seo/analytics`](https://www.npmjs.com/package/@power-seo/analytics)               | `npm i @power-seo/analytics`        | Merge GSC + audit data, trend analysis, ranking insights, dashboard     |
| [`@power-seo/search-console`](https://www.npmjs.com/package/@power-seo/search-console)     | `npm i @power-seo/search-console`   | Google Search Console API — OAuth2, service account, URL inspection     |
| [`@power-seo/integrations`](https://www.npmjs.com/package/@power-seo/integrations)         | `npm i @power-seo/integrations`     | Semrush and Ahrefs API clients with rate limiting and pagination        |
| [`@power-seo/tracking`](https://www.npmjs.com/package/@power-seo/tracking)                 | `npm i @power-seo/tracking`         | GA4, Clarity, PostHog, Plausible, Fathom — scripts + consent management |

---

## About [CyberCraft Bangladesh](https://ccbd.dev)

**[CyberCraft Bangladesh](https://ccbd.dev)** is a Bangladesh-based enterprise-grade software development and Full Stack SEO service provider company specializing in ERP system development, AI-powered SaaS and business applications, full-stack SEO services, custom website development, and scalable eCommerce platforms. We design and develop intelligent, automation-driven SaaS and enterprise solutions that help startups, SMEs, NGOs, educational institutes, and large organizations streamline operations, enhance digital visibility, and accelerate growth through modern cloud-native technologies.

[![Website](https://img.shields.io/badge/Website-ccbd.dev-blue?style=for-the-badge)](https://ccbd.dev)
[![GitHub](https://img.shields.io/badge/GitHub-cybercraftbd-black?style=for-the-badge&logo=github)](https://github.com/cybercraftbd)
[![npm](https://img.shields.io/badge/npm-power--seo-red?style=for-the-badge&logo=npm)](https://www.npmjs.com/org/power-seo)
[![Email](https://img.shields.io/badge/Email-info@ccbd.dev-green?style=for-the-badge&logo=gmail)](mailto:info@ccbd.dev)

© 2026 [CyberCraft Bangladesh](https://ccbd.dev) · Released under the [MIT License](../../LICENSE)