Back

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

Aug 2, 20246 minute read

Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of SEMrush 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:

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

Setting up the project

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

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

Configuring environment variables

Security first! Create a .env file in your project root and add your SEMrush API credentials:

SEMRUSH_CLIENT_ID=your_client_id
SEMRUSH_CLIENT_SECRET=your_client_secret
REDIRECT_URI=http://localhost:3000/callback

Building the authorization flow

Now for the fun part! Let's create our auth flow:

require('dotenv').config(); const express = require('express'); const axios = require('axios'); const app = express(); app.get('/auth', (req, res) => { const authUrl = `https://oauth.semrush.com/oauth2/authorize?client_id=${process.env.SEMRUSH_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://oauth.semrush.com/oauth2/access_token', { client_id: process.env.SEMRUSH_CLIENT_ID, client_secret: process.env.SEMRUSH_CLIENT_SECRET, grant_type: 'authorization_code', code, redirect_uri: process.env.REDIRECT_URI }); const { access_token, refresh_token } = response.data; // Store these tokens securely! res.send('Authorization successful!'); } catch (error) { res.status(500).send('Authorization failed'); } }); app.listen(3000, () => console.log('Server running on port 3000'));

Storing and refreshing tokens

Now that we've got our tokens, let's keep 'em fresh:

async function refreshToken(refresh_token) { try { const response = await axios.post('https://oauth.semrush.com/oauth2/access_token', { client_id: process.env.SEMRUSH_CLIENT_ID, client_secret: process.env.SEMRUSH_CLIENT_SECRET, grant_type: 'refresh_token', refresh_token }); return response.data.access_token; } catch (error) { console.error('Token refresh failed:', error); throw error; } }

Making authenticated requests to SEMrush API

Let's put those shiny new tokens to work:

async function getDomainAnalytics(domain, access_token) { try { const response = await axios.get(`https://api.semrush.com/analytics/v1/`, { params: { type: 'domain_ranks', domain, database: 'us' }, headers: { Authorization: `Bearer ${access_token}` } }); return response.data; } catch (error) { console.error('API request failed:', error); throw error; } }

Error handling and edge cases

Remember, even the best-laid plans can go awry. Always handle those pesky errors and respect API rate limits:

const rateLimit = require('express-rate-limit'); const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); app.use('/api/', apiLimiter);

Best practices and security considerations

Last but not least, let's keep things tight and secure:

  1. Always use HTTPS in production.
  2. Implement CSRF protection (check out the csurf package).
  3. Store sensitive information securely (consider using a service like AWS Secrets Manager).

Wrapping up

And there you have it! You've just built a rock-solid authorization flow for your SEMrush integration. Pat yourself on the back – you've earned it!

Remember, this is just the beginning. From here, you can expand your integration to tap into all sorts of juicy SEMrush data. The SEO world is your oyster!

Happy coding, and may your SERP rankings always be high! 🚀📈