# How to Integrate Bolt.new with Ahrefs

- Tool: Bolt.new
- Difficulty: Intermediate
- Time required: 30 minutes
- Last updated: April 2026

## TL;DR

Integrate Ahrefs with Bolt.new by using the Ahrefs API v3 via a Next.js API route to protect your bearer token. The Ahrefs API enables backlink analysis, keyword tracking, and site audit data in your app. API access requires an Ahrefs subscription on a higher-tier plan. During development in Bolt's WebContainer, outbound API calls work fine; deploy to Netlify or Bolt Cloud before testing webhook callbacks.

## Build an SEO Intelligence Dashboard with Ahrefs and Bolt.new

Ahrefs is the industry standard for backlink analysis, with the web's largest crawled link index outside of Google itself. Its API v3 provides programmatic access to backlink profiles, organic keyword rankings, referring domain counts, URL ratings, and domain ratings — data that power agency dashboards, client reporting tools, and competitive analysis platforms. By connecting Bolt.new to the Ahrefs API, you can build custom SEO monitoring dashboards tailored exactly to your workflow without being constrained by Ahrefs' own UI.

Bolt's WebContainer architecture means all Ahrefs API requests must go through a server-side route. The Ahrefs bearer token is a sensitive credential — if bundled into client-side JavaScript it would be visible in browser DevTools and usable by anyone visiting your app. A Next.js API route running server-side keeps the token in `process.env.AHREFS_API_KEY` and acts as a secure proxy between the browser and Ahrefs. This pattern also lets you add caching, rate limiting, and result transformation before sending data to the frontend.

One important reality to communicate clearly: Ahrefs API access is not included in basic subscriptions. API credits are available on higher-tier plans (Advanced and Enterprise), and each endpoint call costs credits. Building a dashboard that polls Ahrefs every minute would rapidly deplete your allocation. The integration covered here follows a request-on-demand model — fetch data when the user explicitly requests it, cache results locally, and avoid background polling. For teams without Ahrefs API access, the alternatives section covers Moz, SEMrush, and Google Search Console as API-accessible substitutes.

## Before you start

- An Ahrefs account on the Advanced or Enterprise plan with API credits enabled
- Your Ahrefs API bearer token from ahrefs.com/api
- A Bolt.new project using Next.js (required for API routes that proxy the bearer token)
- Basic understanding of SEO metrics: domain rating, backlinks, referring domains, organic traffic
- A deployed Netlify or Bolt Cloud URL if you need to test webhook integrations

## Step-by-step guide

### 1. Get Your Ahrefs API Token and Understand the Credit System

Log in to your Ahrefs account and navigate to ahrefs.com/api or go to Account Settings → API. Ahrefs API v3 uses bearer token authentication — you'll find your token on the API settings page. Copy it carefully and store it somewhere safe. Before integrating, understand how Ahrefs credits work: each API endpoint costs a specific number of credits per call, and your plan has a monthly credit allocation. For example, fetching backlinks for a domain costs credits based on the number of rows returned. The Ahrefs API documentation at developer.ahrefs.com shows the credit cost per endpoint. To avoid burning credits during development, use Ahrefs' sandbox mode if available, or test with a low row limit (set `limit=5` or `limit=10` in API calls during development). Once you have your token, you're ready to configure Bolt. One more thing to check: Ahrefs API v3 base URL is `https://api.ahrefs.com/v3/`. The authorization header format is `Authorization: Bearer YOUR_TOKEN_HERE`. The API returns JSON with a predictable structure — most endpoints return a `data` array with metric objects. Review the API reference for the specific endpoints you'll use (site-explorer/overview, backlinks, organic-keywords) before building your dashboard so you understand the response shape.

```
// lib/ahrefs.ts
const AHREFS_BASE_URL = 'https://api.ahrefs.com/v3';

export async function callAhrefsAPI(
  endpoint: string,
  params: Record<string, string | number> = {}
): Promise<any> {
  const apiKey = process.env.AHREFS_API_KEY;
  if (!apiKey) {
    throw new Error('AHREFS_API_KEY environment variable is not set');
  }

  const url = new URL(`${AHREFS_BASE_URL}/${endpoint}`);
  Object.entries(params).forEach(([key, value]) => {
    url.searchParams.set(key, String(value));
  });

  const response = await fetch(url.toString(), {
    headers: {
      Authorization: `Bearer ${apiKey}`,
      Accept: 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`Ahrefs API error ${response.status}: ${error}`);
  }

  return response.json();
}
```

**Expected result:** The lib/ahrefs.ts utility is ready to use from any Next.js API route. The bearer token stays server-side and never touches client code.

### 2. Create a Domain Overview API Route

Now create the Next.js API route that the frontend will call. This route acts as a secure proxy between your Bolt app and the Ahrefs API — it runs server-side, reads the API key from environment variables, calls Ahrefs, and returns the formatted data to the browser. The key security point is that this route lives in `app/api/` and is never bundled into client-side JavaScript. The browser calls your own Next.js route at `/api/ahrefs/overview?domain=example.com`, your route calls Ahrefs with the bearer token, and returns the response. This pattern prevents your Ahrefs credentials from ever reaching the browser — critical because Ahrefs API credits are tied to your account and leaked credentials could be abused by anyone. The route validates the incoming request, catches API errors gracefully, and formats the Ahrefs response into a clean shape for the frontend. Input validation prevents malicious domains or SQL injection patterns from reaching the Ahrefs API. Always sanitize the domain parameter before using it in API calls.

```
// app/api/ahrefs/overview/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { callAhrefsAPI } from '@/lib/ahrefs';

export async function GET(request: NextRequest) {
  const domain = request.nextUrl.searchParams.get('domain');

  if (!domain) {
    return NextResponse.json(
      { error: 'domain parameter is required' },
      { status: 400 }
    );
  }

  // Basic sanitization
  const cleanDomain = domain.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase();

  try {
    const data = await callAhrefsAPI('site-explorer/overview', {
      target: cleanDomain,
      mode: 'domain',
      limit: 10,
    });

    return NextResponse.json({
      domain: cleanDomain,
      domainRating: data?.metrics?.domain_rating ?? 0,
      backlinks: data?.metrics?.backlinks ?? 0,
      referringDomains: data?.metrics?.referring_domains ?? 0,
      organicTraffic: data?.metrics?.organic_traffic ?? 0,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
```

**Expected result:** Visiting /api/ahrefs/overview?domain=example.com in the browser returns a JSON object with domainRating, backlinks, referringDomains, and organicTraffic values.

### 3. Build the Backlink Analysis Route and Dashboard UI

With the overview route working, extend the integration to fetch actual backlink data. The Ahrefs `site-explorer/backlinks` endpoint returns individual backlinks with their source URL, anchor text, domain rating, link type (follow/nofollow), and first-seen date. This data enables building a proper backlink explorer where users can filter by domain rating, sort by link quality, and identify the most valuable links pointing to any domain. The dashboard UI uses React state to manage the search input, loading states, and the fetched data. Error states must be handled gracefully — Ahrefs returns meaningful error messages when credits are exhausted or when a domain has no data in the index. A key UX consideration: fetching 100 backlinks can take 2-3 seconds over the Ahrefs API. Show a loading spinner and disable the search button while fetching to prevent duplicate requests that would waste credits.

```
// app/api/ahrefs/backlinks/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { callAhrefsAPI } from '@/lib/ahrefs';

export async function GET(request: NextRequest) {
  const domain = request.nextUrl.searchParams.get('domain');
  if (!domain) {
    return NextResponse.json({ error: 'domain is required' }, { status: 400 });
  }

  const cleanDomain = domain.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase();

  try {
    const data = await callAhrefsAPI('site-explorer/backlinks', {
      target: cleanDomain,
      mode: 'domain',
      limit: 20,
      order_by: 'domain_rating_source:desc',
    });

    const backlinks = (data?.backlinks ?? []).map((bl: any) => ({
      urlFrom: bl.url_from,
      domainRating: bl.domain_rating_source,
      anchor: bl.anchor,
      isDofollow: bl.is_dofollow,
      firstSeen: bl.first_seen,
    }));

    return NextResponse.json({ domain: cleanDomain, backlinks });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
```

**Expected result:** The backlinks route returns a JSON array of top backlinks sorted by domain rating. The dashboard UI shows a domain search form and a table that populates after submitting a domain.

### 4. Deploy to Netlify or Bolt Cloud and Set Environment Variables

The Ahrefs API works fine during development in Bolt's WebContainer — outbound HTTPS calls to api.ahrefs.com succeed because WebContainers support all outbound HTTP traffic. However, the `.env` file you created is only for local development. When you deploy to Netlify or Bolt Cloud, the environment variables must be configured in the hosting platform's dashboard — they are not read from the `.env` file in production. For Netlify: connect your Bolt project via Settings → Applications → Netlify, click Publish, then go to the Netlify dashboard → Site Configuration → Environment Variables and add `AHREFS_API_KEY` with your actual bearer token. For Bolt Cloud: click Publish → use the Secrets panel to add the variable before publishing. After adding environment variables, redeploy the site (Netlify triggers a new deploy automatically when env vars change; Bolt Cloud requires re-clicking Publish). Verify the deployment by visiting your deployed URL and testing the domain search form. If the API calls fail on the deployed site but worked in the preview, it's almost always a missing or incorrectly named environment variable.

```
// app/admin/deploy-check/page.tsx
'use client';
import { useState } from 'react';

export default function DeployCheck() {
  const [status, setStatus] = useState<'idle' | 'checking' | 'ok' | 'error'>('idle');
  const [message, setMessage] = useState('');

  const checkConnection = async () => {
    setStatus('checking');
    try {
      const res = await fetch('/api/ahrefs/overview?domain=ahrefs.com');
      const data = await res.json();
      if (res.ok && data.domainRating !== undefined) {
        setStatus('ok');
        setMessage(`Connected. ahrefs.com DR: ${data.domainRating}`);
      } else {
        setStatus('error');
        setMessage(data.error ?? 'Unknown error');
      }
    } catch (e) {
      setStatus('error');
      setMessage('Network error — API route unreachable');
    }
  };

  return (
    <div style={{ padding: 32 }}>
      <h1>Ahrefs API Connection Check</h1>
      <button onClick={checkConnection} disabled={status === 'checking'}>
        {status === 'checking' ? 'Checking...' : 'Test Connection'}
      </button>
      {status === 'ok' && <p style={{ color: 'green' }}>{message}</p>}
      {status === 'error' && <p style={{ color: 'red' }}>Error: {message}</p>}
    </div>
  );
}
```

**Expected result:** After deploying and setting AHREFS_API_KEY in the hosting dashboard, visiting /admin/deploy-check shows a green success message with the Ahrefs domain rating for ahrefs.com.

## Best practices

- Use limit=5 or limit=10 during development to minimize Ahrefs credit consumption while building the integration
- Cache API responses in memory or a simple store for 24 hours — SEO metrics don't change minute-to-minute and caching dramatically reduces credit usage
- Never put the AHREFS_API_KEY in client-side code or expose it in API responses; always proxy through a server-side route
- Validate and sanitize the domain parameter before calling Ahrefs — strip protocols (https://) and paths (/page) to avoid unexpected API errors
- Handle credit exhaustion gracefully with a user-friendly error message rather than a raw API error, since users cannot resolve this themselves
- Use the Ahrefs API reference at developer.ahrefs.com to check credit costs before adding new endpoints — some endpoints are significantly more expensive than others
- Add a request debounce of at least 500ms to prevent users from accidentally triggering multiple API calls by rapidly clicking the search button

## Use cases

### Backlink Profile Dashboard

Build an internal dashboard that shows any domain's backlink count, referring domains, top anchor texts, and recently gained or lost backlinks. Product teams use this to monitor their own site's authority growth and track competitor link-building campaigns. Results update on-demand without leaving Bolt.

Prompt example:

```
Build an SEO backlink dashboard using the Ahrefs API. Create a search field where I can enter any domain. On submit, call a Next.js API route at /api/ahrefs/backlinks that fetches the domain's backlink count, referring domain count, domain rating, and top 10 referring domains from the Ahrefs v3 API. Display results in cards and a table. Store AHREFS_API_KEY in environment variables.
```

### Organic Keyword Tracker

Track which keywords a domain ranks for in organic search, including their current ranking position, estimated search volume, and keyword difficulty. Marketing teams use this to identify quick-win keyword opportunities and track SEO progress over time.

Prompt example:

```
Create a keyword ranking tracker using Ahrefs API. Let me enter a domain and get its top 20 organic keywords from the Ahrefs v3 organic-keywords endpoint. Show each keyword with its position, search volume, keyword difficulty score, and estimated monthly traffic. Proxy all API calls through /api/ahrefs/keywords to protect my bearer token.
```

### Competitor Comparison Tool

Compare your domain against up to three competitors side by side — domain rating, backlink count, referring domains, and estimated organic traffic. Useful for agency pitch decks, competitive audits, and identifying where competitors are winning on SEO.

Prompt example:

```
Build a competitor SEO comparison tool using Ahrefs API. I want to enter my domain and two competitor domains. For each domain, fetch domain rating, backlink count, referring domain count, and estimated organic traffic from Ahrefs v3. Display all three domains in a side-by-side comparison table. Use /api/ahrefs/domain-overview as the proxy route.
```

## Troubleshooting

### API route returns 401 Unauthorized or 'Invalid token'

Cause: The AHREFS_API_KEY environment variable is missing, incorrect, or not yet set in the hosting platform's environment variables panel.

Solution: In development: check that your .env file has AHREFS_API_KEY=your_actual_token (not the placeholder text). In production (Netlify/Bolt Cloud): go to your hosting dashboard, find Environment Variables, and add AHREFS_API_KEY. After adding, redeploy the site — environment variables are injected at build time and require a fresh deploy to take effect.

```
// Verify the variable is being read correctly
console.log('API key present:', !!process.env.AHREFS_API_KEY);
// Only do this in development — never log the actual key value
```

### API returns 429 Too Many Requests or 'Credits exhausted'

Cause: Your Ahrefs plan's monthly API credits have been depleted, or you have hit the rate limit (Ahrefs enforces per-minute request limits).

Solution: For credit exhaustion: wait until your plan renews next month, or upgrade to a higher plan. For rate limiting: add a debounce to the search input so requests don't fire on every keystroke, and add a loading state that disables the search button until the previous request completes.

```
// Add debounce to prevent rapid API calls
import { useMemo } from 'react';
const debouncedSearch = useMemo(
  () => debounce((domain: string) => fetchDomainData(domain), 500),
  []
);
```

### API calls work in Bolt's WebContainer preview but fail after deploying to Netlify

Cause: Environment variables were not added to Netlify's Environment Variables panel before deploying, so process.env.AHREFS_API_KEY is undefined in the serverless function.

Solution: In the Netlify dashboard, go to Site Configuration → Environment Variables and add AHREFS_API_KEY with your bearer token value. Then trigger a new deploy: go to Deploys → Trigger Deploy → Deploy site. Netlify serverless functions read env vars that are set before the deploy, not after.

### Response fields like domain_rating or backlinks are undefined or null

Cause: Ahrefs API response structure varies by endpoint and plan tier. The field path you expect (e.g., data.metrics.domain_rating) may be nested differently in your plan's API version.

Solution: Add a console.log(JSON.stringify(data, null, 2)) inside your API route to log the full raw Ahrefs response in Bolt's terminal. This reveals the actual structure. Update your field access paths to match the actual response shape.

```
// Defensive access with fallbacks
const domainRating = data?.metrics?.domain_rating ?? data?.domain_rating ?? 0;
```

## Frequently asked questions

### Does Ahrefs have a free API tier?

No. The Ahrefs API is available on Advanced and Enterprise plans only, and each API call consumes credits from your monthly allocation. There is no permanently free tier. If you need free SEO data for a Bolt app, Google Search Console API provides authoritative query data for your own properties at no cost.

### Can I call the Ahrefs API directly from the browser in Bolt's preview?

Technically you can make the HTTP call, but you should never do this. Your bearer token would be visible in the browser's network tab and bundled into client-side JavaScript. Anyone who inspects your app could steal your token and use your API credits. Always proxy Ahrefs calls through a Next.js API route where the token lives in process.env.

### How do I handle Ahrefs API rate limits in my Bolt app?

Ahrefs enforces per-minute rate limits in addition to monthly credit quotas. In practice, the credit limit is hit more often than the rate limit for typical dashboards. Add a loading state that disables the search button while a request is in flight, debounce search inputs by 500ms, and cache responses for at least one hour to prevent repeat calls for the same domain.

### Can Bolt.new generate the full Ahrefs integration automatically?

Yes. Prompt Bolt with something like: 'Build an SEO dashboard with Ahrefs API. Create a Next.js API route at /api/ahrefs/overview that fetches domain rating and backlinks using bearer token auth from AHREFS_API_KEY env var. Build a search UI component.' Bolt's AI will generate the route, the fetch utility, and the dashboard component. You'll need to add your actual API key to the .env file manually.

### Does the Ahrefs integration work in Bolt's WebContainer preview?

Yes. Outbound HTTP calls to api.ahrefs.com work fine from the Next.js API route running in Bolt's WebContainer during development. The only limitation is that Bolt's preview cannot receive incoming connections — so Ahrefs alert webhooks (notifications for new backlinks or ranking changes) must be registered with your deployed URL, not the preview URL.

---

Source: https://www.rapidevelopers.com/bolt-ai-integrations/ahrefs
© RapidDev — https://www.rapidevelopers.com/bolt-ai-integrations/ahrefs
