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.
Before we jump in, make sure you've got:
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
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
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'));
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; } }
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; } }
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);
Last but not least, let's keep things tight and secure:
csurf
package).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! 🚀📈