0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【外部パッケージ不要】Node.js標準だけでSearch ConsoleとGA4を0円自動取得するスクリプト(Google Antigravity連携)

0
Posted at

Googleの自律エージェント型開発環境 Google Antigravity を使って複数Webサイトの運用・保守を自動化する中で、外部のnpmパッケージ(googleapis 等)を一切インストールせず、Node.js標準モジュール(node:crypto + fetch)だけで Google Search Console と GA4 のデータを完全無料で一括取得するスクリプトを構築しました。

「毎回管理画面を開いてCSVをエクスポートする手間をなくしたい」「複数のGoogleアカウントに分散したサイトをコマンド1発で横断分析したい」という方の参考になれば幸いです。

※ ツール開発・全ページ自動品質監査・Cursor/Claude Codeとの比較を含めた運用全体のアーキテクチャ実録は、別記事の Google Antigravityで何ができる?AI駆動開発とSearch Console・GA4の0円自動分析を仕組み化した実録 にまとめています。


この構成のメリット

  1. 完全無料(0円)・回数制限の心配なし
    • Google Search Console API・GA4 Data API ともに標準利用は無料です。Google Cloud プロジェクトに請求先(クレジットカード)を紐づけなければ課金は発生しません。
  2. 依存パッケージゼロ(npm install 不要)
    • node:crypto でサービスアカウントの JWT(RS256)を自前署名して OAuth2 トークンを取得するため、Node.js 18+ があればそのまま動きます。
  3. 別々のGoogleアカウントにある複数サイトも一括取得
    • 発行したサービスアカウントのメールアドレス1つを各サイトの Search Console(制限付き)/GA4(閲覧者)に招待するだけで、アカウントをまたいで自動取得できます。

事前準備:Google Cloud 側の5ステップ(約5分)

  1. Google Cloud Console で新規プロジェクトを作成(請求先アカウントの登録は不要)。
  2. 「APIとサービス > ライブラリ」から以下 3つのAPI を有効化:
    • Google Search Console API
    • Google Analytics Data API
    • Google Analytics Admin API(GA4プロパティIDの自動検出に使用)
  3. 「IAMと管理 > サービス アカウント」から新規作成。
    • ポイント:途中の「②権限(省略可)」「③アクセス権を持つプリンシパル(省略可)」は**空欄のまま「完了」**でOKです。
  4. 作成したサービスアカウントの「キー」タブ >「鍵を追加」>「新しい鍵を作成」> JSON をダウンロードし、リポジトリ外の安全な場所へ保存(例:./service-account.json)。
  5. サービスアカウントのメールアドレス(xxx@xxx.iam.gserviceaccount.com)を、取得したい各サイトの以下に招待:
    • Search Console:設定 > ユーザーと権限 > ユーザーを追加(権限:制限付き)
    • GA4:管理 > プロパティのアクセス管理 > ユーザーを追加(役割:閲覧者)

実装コード:fetch-analytics.mjs(外部パッケージ不要)

import fs from 'node:fs';
import crypto from 'node:crypto';

/**
 * Node.js標準モジュールのみで Search Console & GA4 を一括取得するスクリプト
 * 使い方:
 *   GOOGLE_APPLICATION_CREDENTIALS=./service-account.json node fetch-analytics.mjs --days 28
 */

const args = process.argv.slice(2);
const getArg = (flag, fallback) => {
  const idx = args.indexOf(flag);
  return idx !== -1 && args[idx + 1] ? args[idx + 1] : fallback;
};

const keyPath = getArg('--key', process.env.GOOGLE_APPLICATION_CREDENTIALS || './service-account.json');
const days = Math.max(Number(getArg('--days', '28')) || 28, 1);
const siteFilter = getArg('--site', '');

function base64url(input) {
  return Buffer.from(input)
    .toString('base64')
    .replace(/=/g, '')
    .replace(/\+/g, '-')
    .replace(/\//g, '_');
}

async function getAccessToken(sa, scopes) {
  const now = Math.floor(Date.now() / 1000);
  const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
  const claim = base64url(
    JSON.stringify({
      iss: sa.client_email,
      scope: scopes.join(' '),
      aud: 'https://oauth2.googleapis.com/token',
      iat: now,
      exp: now + 3600,
    })
  );
  const unsigned = `${header}.${claim}`;
  const sign = crypto.createSign('RSA-SHA256');
  sign.update(unsigned);
  sign.end();
  const sig = base64url(sign.sign(sa.private_key));

  const res = await fetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      assertion: `${unsigned}.${sig}`,
    }),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`OAuth token error (${res.status}): ${JSON.stringify(json)}`);
  return json.access_token;
}

const fmt = (d) => d.toISOString().slice(0, 10);

async function fetchGSC(token, startDate, endDate) {
  const listRes = await fetch('https://www.googleapis.com/webmasters/v3/sites', {
    headers: { Authorization: `Bearer ${token}` },
  });
  const listJson = await listRes.json();
  const sites = (listJson.siteEntry || []).filter((s) => !siteFilter || s.siteUrl.includes(siteFilter));

  console.log(`\n=== Search Console (${startDate} 〜 ${endDate}) ===`);
  for (const s of sites) {
    console.log(`\nサイト: ${s.siteUrl}`);
    const res = await fetch(
      `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(s.siteUrl)}/searchAnalytics/query`,
      {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ startDate, endDate, dimensions: ['page'], rowLimit: 10 }),
      }
    );
    const json = await res.json();
    for (const r of json.rows || []) {
      console.log(
        `  Imp:${r.impressions} | Click:${r.clicks} | CTR:${(r.ctr * 100).toFixed(1)}% | 順位:${r.position.toFixed(1)} | ${r.keys[0]}`
      );
    }
  }
}

async function fetchGA4(token, startDate, endDate) {
  const sumRes = await fetch('https://analyticsadmin.googleapis.com/v1beta/accountSummaries', {
    headers: { Authorization: `Bearer ${token}` },
  });
  const sumJson = await sumRes.json();
  console.log(`\n=== GA4 (${startDate} 〜 ${endDate}) ===`);

  for (const acc of sumJson.accountSummaries || []) {
    for (const p of acc.propertySummaries || []) {
      const propId = p.property.replace('properties/', '');
      console.log(`\nプロパティ: ${p.displayName} (ID: ${propId})`);
      const repRes = await fetch(`https://analyticsdata.googleapis.com/v1beta/properties/${propId}:runReport`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          dateRanges: [{ startDate, endDate }],
          dimensions: [{ name: 'sessionSourceMedium' }],
          metrics: [{ name: 'activeUsers' }, { name: 'sessions' }, { name: 'screenPageViews' }],
          limit: 10,
        }),
      });
      const repJson = await repRes.json();
      for (const r of repJson.rows || []) {
        console.log(
          `  ${r.dimensionValues[0].value} | Users:${r.metricValues[0].value} | PV:${r.metricValues[2].value}`
        );
      }
    }
  }
}

const sa = JSON.parse(fs.readFileSync(keyPath, 'utf8'));
const token = await getAccessToken(sa, [
  'https://www.googleapis.com/auth/webmasters.readonly',
  'https://www.googleapis.com/auth/analytics.readonly',
]);
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - days);

await fetchGSC(token, fmt(start), fmt(end));
await fetchGA4(token, fmt(start), fmt(end));

Google Antigravity との組み合わせ運用

このスクリプトと認証JSONキーをプロジェクト外の共通設定フォルダに置き、Antigravityのグローバルルールファイルへ実行コマンドを記載しておくと、別プロジェクトの会話からでも「最新のサーチコンソールとGA4を確認して」と伝えるだけで自動取得・改善提案まで完結します。

※ JSONキーはリポジトリや配布ZIPに絶対に含めないよう、必ず .gitignore 対象外またはプロジェクト外ディレクトリで管理してください。


まとめ

  • Node.js標準モジュール(node:crypto + fetch)だけで Google 公式API の JWT 認証〜Search Console / GA4 取得まで約120行で実装可能。
  • サービスアカウント1つを各サイトへ閲覧権限で招待すれば、別々のGoogleアカウントにある複数サイトも横断分析できる。

WordPress子テーマ開発や全ページ品質監査を含めた実運用全体の詳細・構成図は、こちらの記事でも詳しく解説しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?