Hey there, fellow developer! Ready to supercharge your SEO tools with Ahrefs data? You're in the right place. We're going to walk through building an Ahrefs API integration using the nifty node-ahrefs
package. Buckle up!
Before we dive in, make sure you've got:
Let's get our project off the ground:
mkdir ahrefs-integration && cd ahrefs-integration npm init -y npm install node-ahrefs
Easy peasy, right?
Now, let's set up our Ahrefs client:
const Ahrefs = require('node-ahrefs'); const client = new Ahrefs('YOUR_API_TOKEN');
Replace 'YOUR_API_TOKEN'
with your actual token, and you're good to go!
The node-ahrefs
package makes it super simple to interact with various Ahrefs endpoints. Here are a couple of examples to get you started:
// Fetching backlink data client.backlinks.getRefDomains('example.com', { mode: 'domain' }) .then(data => console.log(data)) .catch(err => console.error(err)); // Retrieving keyword difficulty client.keywords.getMetrics(['seo', 'backlinks']) .then(data => console.log(data)) .catch(err => console.error(err));
Ahrefs API returns JSON responses. Here's how you might handle them:
client.backlinks.getRefDomains('example.com', { mode: 'domain' }) .then(data => { const refDomains = data.refdomains; console.log(`Total referring domains: ${refDomains}`); }) .catch(err => { console.error('Oops! Something went wrong:', err.message); });
Ahrefs API has rate limits, so let's be good citizens and implement some basic throttling:
const { promisify } = require('util'); const sleep = promisify(setTimeout); async function throttledRequest(fn, ...args) { const result = await fn(...args); await sleep(1000); // Wait 1 second between requests return result; } // Usage throttledRequest(client.backlinks.getRefDomains, 'example.com', { mode: 'domain' }) .then(data => console.log(data)) .catch(err => console.error(err));
Let's put it all together in a simple command-line tool:
const Ahrefs = require('node-ahrefs'); const readline = require('readline'); const client = new Ahrefs('YOUR_API_TOKEN'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter a domain to analyze: ', (domain) => { client.backlinks.getRefDomains(domain, { mode: 'domain' }) .then(data => { console.log(`Domain: ${domain}`); console.log(`Referring domains: ${data.refdomains}`); console.log(`Backlinks: ${data.backlinks}`); }) .catch(err => console.error('Error:', err.message)) .finally(() => rl.close()); });
const client = new Ahrefs(process.env.AHREFS_API_TOKEN);
And there you have it! You've just built a basic Ahrefs API integration. Remember, this is just scratching the surface. The Ahrefs API offers a wealth of data, so don't be afraid to explore and experiment.
For more details, check out the Ahrefs API documentation and the node-ahrefs package.
Now go forth and build some awesome SEO tools! 🚀