Skip to main content
RapidDev - Software Development Agency
bolt-ai-integrationsBolt Chat + API Route

How to Integrate Bolt.new with Ahrefs

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.

What you'll learn

  • How to get Ahrefs API access and generate a bearer token
  • How to create a Next.js API route that proxies Ahrefs API calls server-side
  • How to fetch backlink data and keyword rankings for any domain
  • How to build an SEO monitoring dashboard in Bolt.new with Ahrefs data
  • How to handle Ahrefs' credit-metered pricing to avoid unexpected costs
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate14 min read30 minutesSEOApril 2026RapidDev Engineering Team
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.

Integration method

Bolt Chat + API Route

Ahrefs API v3 uses bearer token authentication over HTTPS. Because the token must never be exposed in client-side code, all API calls are proxied through a Next.js API route running server-side. Bolt's AI generates the route and the React dashboard components from a single prompt. The Ahrefs API is credit-metered — each endpoint call consumes credits from your plan, so avoid fetching large datasets unnecessarily.

Prerequisites

  • 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.

Bolt.new Prompt

Set up Ahrefs API integration. Create a .env file with AHREFS_API_KEY=your_bearer_token_here as a placeholder. Create a lib/ahrefs.ts file that exports an async function callAhrefsAPI(endpoint: string, params: Record<string, string>) that makes an authenticated GET request to https://api.ahrefs.com/v3/{endpoint} with the bearer token from process.env.AHREFS_API_KEY and the params as query string.

Paste this in Bolt.new chat

lib/ahrefs.ts
1// lib/ahrefs.ts
2const AHREFS_BASE_URL = 'https://api.ahrefs.com/v3';
3
4export async function callAhrefsAPI(
5 endpoint: string,
6 params: Record<string, string | number> = {}
7): Promise<any> {
8 const apiKey = process.env.AHREFS_API_KEY;
9 if (!apiKey) {
10 throw new Error('AHREFS_API_KEY environment variable is not set');
11 }
12
13 const url = new URL(`${AHREFS_BASE_URL}/${endpoint}`);
14 Object.entries(params).forEach(([key, value]) => {
15 url.searchParams.set(key, String(value));
16 });
17
18 const response = await fetch(url.toString(), {
19 headers: {
20 Authorization: `Bearer ${apiKey}`,
21 Accept: 'application/json',
22 },
23 });
24
25 if (!response.ok) {
26 const error = await response.text();
27 throw new Error(`Ahrefs API error ${response.status}: ${error}`);
28 }
29
30 return response.json();
31}

Pro tip: Set limit=5 in all API calls during development to minimize credit consumption while building the dashboard. Switch to your desired limit (50-100) once the integration is working correctly.

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.

Bolt.new Prompt

Create a Next.js API route at app/api/ahrefs/overview/route.ts that accepts a GET request with a 'domain' query parameter. Use the callAhrefsAPI function from lib/ahrefs.ts to fetch the domain's overview from the site-explorer/overview endpoint with these params: target=domain, mode=domain, date=today. Return the domain_rating, backlinks, and referring_domains from the response. Return a 400 error if no domain is provided.

Paste this in Bolt.new chat

app/api/ahrefs/overview/route.ts
1// app/api/ahrefs/overview/route.ts
2import { NextRequest, NextResponse } from 'next/server';
3import { callAhrefsAPI } from '@/lib/ahrefs';
4
5export async function GET(request: NextRequest) {
6 const domain = request.nextUrl.searchParams.get('domain');
7
8 if (!domain) {
9 return NextResponse.json(
10 { error: 'domain parameter is required' },
11 { status: 400 }
12 );
13 }
14
15 // Basic sanitization
16 const cleanDomain = domain.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase();
17
18 try {
19 const data = await callAhrefsAPI('site-explorer/overview', {
20 target: cleanDomain,
21 mode: 'domain',
22 limit: 10,
23 });
24
25 return NextResponse.json({
26 domain: cleanDomain,
27 domainRating: data?.metrics?.domain_rating ?? 0,
28 backlinks: data?.metrics?.backlinks ?? 0,
29 referringDomains: data?.metrics?.referring_domains ?? 0,
30 organicTraffic: data?.metrics?.organic_traffic ?? 0,
31 });
32 } catch (error) {
33 const message = error instanceof Error ? error.message : 'Unknown error';
34 return NextResponse.json({ error: message }, { status: 500 });
35 }
36}

Pro tip: The Ahrefs API response structure can vary between plan tiers. Log the raw response during development with console.log(data) in the API route — it's visible in Bolt's terminal panel, not the browser, keeping it private.

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.

Bolt.new Prompt

Create a Next.js API route at app/api/ahrefs/backlinks/route.ts that fetches the top 20 backlinks for a domain using the Ahrefs site-explorer/backlinks endpoint. Return each backlink's url_from, domain_rating_source, anchor, is_dofollow, and first_seen. Then build a React component SeoDashboard.tsx with a domain search form, loading state, and a table showing the results. Fetch from /api/ahrefs/backlinks on form submit.

Paste this in Bolt.new chat

app/api/ahrefs/backlinks/route.ts
1// app/api/ahrefs/backlinks/route.ts
2import { NextRequest, NextResponse } from 'next/server';
3import { callAhrefsAPI } from '@/lib/ahrefs';
4
5export async function GET(request: NextRequest) {
6 const domain = request.nextUrl.searchParams.get('domain');
7 if (!domain) {
8 return NextResponse.json({ error: 'domain is required' }, { status: 400 });
9 }
10
11 const cleanDomain = domain.replace(/[^a-zA-Z0-9.-]/g, '').toLowerCase();
12
13 try {
14 const data = await callAhrefsAPI('site-explorer/backlinks', {
15 target: cleanDomain,
16 mode: 'domain',
17 limit: 20,
18 order_by: 'domain_rating_source:desc',
19 });
20
21 const backlinks = (data?.backlinks ?? []).map((bl: any) => ({
22 urlFrom: bl.url_from,
23 domainRating: bl.domain_rating_source,
24 anchor: bl.anchor,
25 isDofollow: bl.is_dofollow,
26 firstSeen: bl.first_seen,
27 }));
28
29 return NextResponse.json({ domain: cleanDomain, backlinks });
30 } catch (error) {
31 const message = error instanceof Error ? error.message : 'Unknown error';
32 return NextResponse.json({ error: message }, { status: 500 });
33 }
34}

Pro tip: Order backlinks by domain_rating_source:desc to show the most authoritative links first — this is the most actionable view for SEO analysis and minimizes the rows you need to fetch to get valuable insights.

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.

Bolt.new Prompt

Add a deployment checklist to my Bolt.new app. Create a simple /admin/deploy-check page (no auth required for this internal tool) that tests the Ahrefs API connection by calling /api/ahrefs/overview?domain=ahrefs.com and shows whether the API key is configured correctly and the API is reachable.

Paste this in Bolt.new chat

app/admin/deploy-check/page.tsx
1// app/admin/deploy-check/page.tsx
2'use client';
3import { useState } from 'react';
4
5export default function DeployCheck() {
6 const [status, setStatus] = useState<'idle' | 'checking' | 'ok' | 'error'>('idle');
7 const [message, setMessage] = useState('');
8
9 const checkConnection = async () => {
10 setStatus('checking');
11 try {
12 const res = await fetch('/api/ahrefs/overview?domain=ahrefs.com');
13 const data = await res.json();
14 if (res.ok && data.domainRating !== undefined) {
15 setStatus('ok');
16 setMessage(`Connected. ahrefs.com DR: ${data.domainRating}`);
17 } else {
18 setStatus('error');
19 setMessage(data.error ?? 'Unknown error');
20 }
21 } catch (e) {
22 setStatus('error');
23 setMessage('Network error — API route unreachable');
24 }
25 };
26
27 return (
28 <div style={{ padding: 32 }}>
29 <h1>Ahrefs API Connection Check</h1>
30 <button onClick={checkConnection} disabled={status === 'checking'}>
31 {status === 'checking' ? 'Checking...' : 'Test Connection'}
32 </button>
33 {status === 'ok' && <p style={{ color: 'green' }}>{message}</p>}
34 {status === 'error' && <p style={{ color: 'red' }}>Error: {message}</p>}
35 </div>
36 );
37}

Pro tip: Bolt's WebContainer cannot receive incoming connections, so there is no webhook support during development. If you plan to use Ahrefs' alert webhooks (for new backlinks, ranking changes), register the webhook URL with your deployed domain, not the preview URL.

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.

Common 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.

Bolt.new Prompt

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.

Copy this prompt to try it in Bolt.new

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.

Bolt.new Prompt

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.

Copy this prompt to try it in Bolt.new

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.

Bolt.new Prompt

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.

Copy this prompt to try it in Bolt.new

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.

typescript
1// Verify the variable is being read correctly
2console.log('API key present:', !!process.env.AHREFS_API_KEY);
3// 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.

typescript
1// Add debounce to prevent rapid API calls
2import { useMemo } from 'react';
3const debouncedSearch = useMemo(
4 () => debounce((domain: string) => fetchDomainData(domain), 500),
5 []
6);

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.

typescript
1// Defensive access with fallbacks
2const domainRating = data?.metrics?.domain_rating ?? data?.domain_rating ?? 0;

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

Alternatives

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.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.