Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(semrush): route backlinks reports to the analytics endpoint

Rudy Celekli9125cefa9661
diff --git a/tests/clis/semrush-backlinks-route.test.cjs b/tests/clis/semrush-backlinks-route.test.cjs
new file mode 100644
index 0000000..53ade10
--- /dev/null
+++ b/tests/clis/semrush-backlinks-route.test.cjs
@@ -0,0 +1,45 @@
+const { test } = require('node:test')
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+
+const cli = path.resolve(__dirname, '../../tools/clis/semrush.js')
+function run(args, fetchSource) {
+ const setup = fetchSource || "global.fetch = async () => { throw new Error('unexpected network request') }"
+ const source = `${setup}; process.argv = ['node', ${JSON.stringify(cli)}, ...${JSON.stringify(args)}]; require(${JSON.stringify(cli)});`
+ const result = spawnSync(process.execPath, ['-e', source], { encoding: 'utf8', env: { ...process.env, SEMRUSH_API_KEY: 'fixture-secret' } })
+ assert.equal(result.status, 0, result.stderr)
+ return JSON.parse(result.stdout)
+}
+for (const command of ['overview', 'list']) {
+ test(`backlinks ${command} previews the documented analytics/v1 endpoint with masked key`, () => {
+ const output = run(['backlinks', command, '--target', 'example.com', '--limit', '5', '--dry-run'])
+ const url = new URL(output.url)
+ assert.equal(url.pathname, '/analytics/v1/')
+ assert.equal(url.searchParams.get('type'), command === 'overview' ? 'backlinks_overview' : 'backlinks')
+ assert.equal(url.searchParams.get('target'), 'example.com')
+ assert.equal(url.searchParams.get('target_type'), 'root_domain')
+ assert.equal(url.searchParams.get('key'), '***')
+ assert.equal(JSON.stringify(output).includes('fixture-secret'), false)
+ if (command === 'list') assert.equal(url.searchParams.get('display_limit'), '5')
+ })
+ test(`backlinks ${command} sends the analytics request and preserves escaped CSV parsing`, () => {
+ const output = run(['backlinks', command, '--target', 'example.com'], `global.fetch = async value => {
+ const url = new URL(value)
+ if (url.pathname !== '/analytics/v1/') throw new Error('Backlinks reports use the analytics endpoint')
+ if (url.searchParams.get('key') !== 'fixture-secret') throw new Error('missing key')
+ if (url.searchParams.get('export_escape') !== '1') throw new Error('missing CSV escaping')
+ return { ok: true, status: 200, text: async () => ${JSON.stringify('"source_title";"anchor"\r\n"Example; title";"Visit"\r\n')} }
+ }`)
+ assert.deepEqual(output, [{ source_title: 'Example; title', anchor: 'Visit' }])
+ })
+ test(`backlinks ${command} does not send an undefined target`, () => {
+ assert.deepEqual(run(['backlinks', command]), { error: '--target required' })
+ })
+}
+test('domain and keyword reports retain their standard API endpoint', () => {
+ for (const args of [['domain', 'organic', '--domain', 'example.com'], ['keywords', 'overview', '--phrase', 'summer shoes']]) {
+ const output = run([...args, '--dry-run'])
+ assert.equal(new URL(output.url).pathname, '/')
+ }
+})
diff --git a/tools/clis/semrush.js b/tools/clis/semrush.js
index 07c5ca0..496c810 100755
--- a/tools/clis/semrush.js
+++ b/tools/clis/semrush.js
@@ -3,6 +3,7 @@
const rawArgs = process.argv.slice(2)
const API_KEY = process.env.SEMRUSH_API_KEY
const BASE_URL = 'https://api.semrush.com/'
+const BACKLINKS_URL = 'https://api.semrush.com/analytics/v1/'
if ((!API_KEY) && rawArgs.length > 0) {
console.error(JSON.stringify({ error: 'SEMRUSH_API_KEY environment variable required' }))
@@ -45,15 +46,15 @@ function parseCSV(text) {
return rows.map(cells => Object.fromEntries(headers.map((header, index) => [header, cells[index] || ''])))
}
-async function api(params) {
+async function api(params, baseUrl = BASE_URL) {
params.set('key', API_KEY)
params.set('export_escape', '1')
if (args['dry-run']) {
const maskedParams = new URLSearchParams(params)
maskedParams.set('key', '***')
- return { _dry_run: true, method: 'GET', url: `${BASE_URL}?${maskedParams}`, headers: {}, body: undefined }
+ return { _dry_run: true, method: 'GET', url: `${baseUrl}?${maskedParams}`, headers: {}, body: undefined }
}
- const res = await fetch(`${BASE_URL}?${params}`)
+ const res = await fetch(`${baseUrl}?${params}`)
const text = await res.text()
if (!res.ok) {
return { error: text.trim(), status: res.status }
@@ -177,15 +178,17 @@ async function main() {
case 'backlinks':
switch (sub) {
case 'overview': {
+ if (!args.target) { result = { error: '--target required' }; break }
const params = new URLSearchParams({
type: 'backlinks_overview',
target: args.target,
target_type: 'root_domain',
})
- result = await api(params)
+ result = await api(params, BACKLINKS_URL)
break
}
case 'list': {
+ if (!args.target) { result = { error: '--target required' }; break }
const params = new URLSearchParams({
type: 'backlinks',
target: args.target,
@@ -193,7 +196,7 @@ async function main() {
export_columns: 'source_url,source_title,target_url,anchor',
})
if (args.limit) params.set('display_limit', args.limit)
- result = await api(params)
+ result = await api(params, BACKLINKS_URL)
break
}
default: