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.
Before we jump in, make sure you've got:
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
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
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}`); });
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); } }
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'); } });
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!'); });
Fire up your server and test the flow:
http://localhost:3000/auth
http://localhost:3000/api-call
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.
Now go forth and conquer the SEO world with your shiny new Ahrefs integration! Happy coding!