Back

How to build a public Ahrefs integration: Building the Auth Flow

Aug 7, 20246 minute read

Hey there, fellow JavaScript enthusiast! Ready to dive into the world of Ahrefs API integration? Let's roll up our sleeves and build an authorization flow that'll make your users feel like they've got the keys to the SEO kingdom.

Prerequisites

Before we jump in, make sure you've got:

  • Ahrefs API access (if you don't, go grab it!)
  • Node.js and npm installed on your machine
  • A solid grasp of OAuth 2.0 (don't worry, we'll refresh your memory)

Setting up the project

First things first, let's get our project off the ground:

mkdir ahrefs-integration && cd ahrefs-integration npm init -y npm install express axios dotenv

Configuring environment variables

Create a .env file in your project root and add your Ahrefs API credentials:

AHREFS_CLIENT_ID=your_client_id
AHREFS_CLIENT_SECRET=your_client_secret
REDIRECT_URI=http://localhost:3000/callback

Implementing the authorization flow

Now, let's create a simple Express server to handle our auth flow:

require('dotenv').config(); const express = require('express'); const axios = require('axios'); const app = express(); const port = 3000; app.get('/auth', (req, res) => { const authUrl = `https://app.ahrefs.com/api/auth?client_id=${process.env.AHREFS_CLIENT_ID}&redirect_uri=${process.env.REDIRECT_URI}&response_type=code`; res.redirect(authUrl); }); app.get('/callback', async (req, res) => { const { code } = req.query; try { const response = await axios.post('https://app.ahrefs.com/api/token', { client_id: process.env.AHREFS_CLIENT_ID, client_secret: process.env.AHREFS_CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: process.env.REDIRECT_URI }); const { access_token, refresh_token } = response.data; // Store these tokens securely (more on this later) res.send('Authorization successful!'); } catch (error) { console.error('Error during token exchange:', error.response.data); res.status(500).send('Authorization failed'); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

Storing and managing tokens

Now that we've got our tokens, we need to store them securely. In a production environment, you'd want to use a database, but for now, let's keep it simple with in-memory storage:

let tokens = {}; // After successful token exchange tokens = { access_token, refresh_token, expires_at: Date.now() + (response.data.expires_in * 1000) }; // Function to refresh token when needed async function refreshToken() { try { const response = await axios.post('https://app.ahrefs.com/api/token', { client_id: process.env.AHREFS_CLIENT_ID, client_secret: process.env.AHREFS_CLIENT_SECRET, refresh_token: tokens.refresh_token, grant_type: 'refresh_token' }); tokens = { access_token: response.data.access_token, refresh_token: response.data.refresh_token, expires_at: Date.now() + (response.data.expires_in * 1000) }; } catch (error) { console.error('Error refreshing token:', error); } }

Making authenticated requests to Ahrefs API

Let's add a simple endpoint to make an API call:

app.get('/api-call', async (req, res) => { if (Date.now() >= tokens.expires_at) { await refreshToken(); } try { const response = await axios.get('https://api.ahrefs.com/v3/site-explorer/overview', { headers: { Authorization: `Bearer ${tokens.access_token}` }, params: { target: 'ahrefs.com' } }); res.json(response.data); } catch (error) { console.error('API call failed:', error); res.status(500).send('API call failed'); } });

Error handling and edge cases

Always be prepared for the unexpected! Here's a simple middleware to handle errors:

app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });

Testing the integration

Fire up your server and test the flow:

  1. Visit http://localhost:3000/auth
  2. Complete the Ahrefs authorization
  3. Try making an API call at http://localhost:3000/api-call

Conclusion

And there you have it! You've just built a basic Ahrefs integration with a solid auth flow. Remember, this is just the beginning. As you expand your integration, consider implementing more robust error handling, secure token storage, and additional API endpoints.

Additional resources

Now go forth and conquer the SEO world with your shiny new Ahrefs integration! Happy coding!