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でGA4データを取得する:GA Lite API連携ガイド

0
Posted at

GA4 の数値をダッシュボードやバッチ処理から扱いたい場合、Google Analytics Data API を直接組み込む方法もありますが、認証や複数サイト管理の実装が少し重くなりがちです。

GA Lite は、GA4、Google Search Console、Bing Webmaster Tools のデータを読み取り専用の JSON API として扱えるサービスです。公式サイトにログインするとアカウント設定から API key を発行でき、その key を Bearer token として送るだけで Node.js からサイト指標を取得できます。

この記事では、GA Lite API を Node.js から呼び出し、GA4 のサマリー、時系列、ディメンション別データ、リアルタイムデータを取得する最小構成をまとめます。

前提

  • Node.js 18 以上
  • GA Lite 側で対象サイトの GA4 連携が済んでいること
  • GA Lite の API key
  • 対象サイトの projectKey

API の base URL は次です。

https://galite.io/api/v1

認証は共通して Authorization ヘッダーに Bearer token を付けます。

Authorization: Bearer sk_live_xxxxxxxxxxxxx

API key は公開リポジトリやフロントエンドに置かず、必ずサーバー側の環境変数として扱います。

環境変数

ローカルでは次のように設定しておきます。

export GALITE_API_KEY="sk_live_xxxxxxxxxxxxx"
export GALITE_PROJECT_KEY="your_project_key"

Windows PowerShell の場合は次の形です。

$env:GALITE_API_KEY="sk_live_xxxxxxxxxxxxx"
$env:GALITE_PROJECT_KEY="your_project_key"

projectKey が分からない場合は、後述の /projects/list で確認できます。

API クライアントを作る

Node.js 18 以降なら標準の fetch が使えるため、依存パッケージなしで実装できます。

// index.mjs
const BASE_URL = "https://galite.io/api/v1";

const apiKey = process.env.GALITE_API_KEY;

if (!apiKey) {
  throw new Error("GALITE_API_KEY is required");
}

async function requestGalite(path, options = {}) {
  const { method = "GET", query, body } = options;
  const url = new URL(`${BASE_URL}${path}`);

  if (query) {
    for (const [key, value] of Object.entries(query)) {
      if (value !== undefined && value !== null) {
        url.searchParams.set(key, String(value));
      }
    }
  }

  const response = await fetch(url, {
    method,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      Accept: "application/json",
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  const text = await response.text();
  const data = text ? JSON.parse(text) : null;

  if (!response.ok) {
    throw new Error(`${response.status} ${response.statusText}: ${text}`);
  }

  return data;
}

レスポンスは JSON で返るので、まずは console.dir(data, { depth: null }) で実際の構造を確認しながら、必要なフィールドをアプリケーション側の型に落とし込むのが扱いやすいです。

プロジェクト一覧を取得する

最初に、自分の API key でアクセスできるプロジェクトを確認します。

const projects = await requestGalite("/projects/list");
console.dir(projects, { depth: null });

ここで対象サイトの projectKey を確認します。以降の GA4 系エンドポイントでは、この projectKey を URL に含めます。

GA4 サマリーを取得する

サイト全体の概要指標を取得するには /metrics/{projectKey}/summary を使います。

const projectKey = process.env.GALITE_PROJECT_KEY;

if (!projectKey) {
  throw new Error("GALITE_PROJECT_KEY is required");
}

const summary = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/summary`,
  {
    query: {
      period: "28days",
    },
  },
);

console.dir(summary, { depth: null });

period には todayyesterday7days28days90days180days365dayscustom_START_END 形式が使えます。

例えば任意期間を指定したい場合は、次のようなイメージです。

const customSummary = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/summary`,
  {
    query: {
      period: "custom_2026-07-01_2026-07-21",
    },
  },
);

時系列データを取得する

PV の推移など、日別のグラフに使うデータは /timeseries から取得します。

const pageViews = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/timeseries`,
  {
    query: {
      period: "28days",
      metric: "screenPageViews",
    },
  },
);

console.dir(pageViews, { depth: null });

管理画面で折れ線グラフを作る場合は、このレスポンスを日付順に整形してフロントエンドへ返すだけで十分です。

国別やページ別などのディメンションで集計する

国、ページ、参照元など、軸を指定して集計したい場合は /dimension を使います。

const countries = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/dimension`,
  {
    query: {
      dimension: "country",
      period: "28days",
    },
  },
);

console.dir(countries, { depth: null });

dimension を変えれば、同じクライアントで別軸のランキングや内訳を作れます。API の返却構造を確認したうえで、必要に応じて上位 N 件だけを保存したり、キャッシュしたりすると運用しやすくなります。

リアルタイムデータを取得する

現在のアクセス状況を軽く表示したい場合は /realtime を使います。

const realtime = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/realtime`,
);

console.dir(realtime, { depth: null });

リアルタイム値は画面表示のたびに叩くよりも、短い TTL のキャッシュを挟むほうが安定します。管理画面であれば 30 秒から 60 秒程度のキャッシュでも実用上は十分なことが多いです。

まとめて取得するサンプル

実際の管理画面やレポート API では、複数の指標を並列で取得してまとめて返す形が便利です。

// index.mjs
const BASE_URL = "https://galite.io/api/v1";

const apiKey = process.env.GALITE_API_KEY;
const projectKey = process.env.GALITE_PROJECT_KEY;

if (!apiKey) throw new Error("GALITE_API_KEY is required");
if (!projectKey) throw new Error("GALITE_PROJECT_KEY is required");

async function requestGalite(path, options = {}) {
  const { method = "GET", query, body } = options;
  const url = new URL(`${BASE_URL}${path}`);

  if (query) {
    for (const [key, value] of Object.entries(query)) {
      if (value !== undefined && value !== null) {
        url.searchParams.set(key, String(value));
      }
    }
  }

  const response = await fetch(url, {
    method,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      Accept: "application/json",
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  const text = await response.text();
  const data = text ? JSON.parse(text) : null;

  if (!response.ok) {
    throw new Error(`${response.status} ${response.statusText}: ${text}`);
  }

  return data;
}

async function main() {
  const encodedProjectKey = encodeURIComponent(projectKey);
  const period = process.argv[2] ?? "28days";

  const [summary, pageViews, countries, realtime] = await Promise.all([
    requestGalite(`/metrics/${encodedProjectKey}/summary`, {
      query: { period },
    }),
    requestGalite(`/metrics/${encodedProjectKey}/timeseries`, {
      query: { period, metric: "screenPageViews" },
    }),
    requestGalite(`/metrics/${encodedProjectKey}/dimension`, {
      query: { period, dimension: "country" },
    }),
    requestGalite(`/metrics/${encodedProjectKey}/realtime`),
  ]);

  console.dir(
    {
      summary,
      pageViews,
      countries,
      realtime,
    },
    { depth: null },
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

実行します。

node index.mjs 28days

Google Search Console / Bing データも同じ認証で取得できる

GA Lite API では、検索系の指標も同じ Bearer token で取得できます。

const searchSummary = await requestGalite(
  `/metrics/${encodeURIComponent(projectKey)}/search/summary`,
  {
    query: {
      period: "28days",
      sp: "all",
    },
  },
);

console.dir(searchSummary, { depth: null });

spallgscbing を指定できます。GA4 のアクセスデータと検索流入データを同じバッチで取得できるため、週次レポートや社内ダッシュボードにまとめやすいです。

ネイティブ GA4 形式が必要な場合

通常は /summary/timeseries/dimension のような整理済みエンドポイントを使うほうが実装はシンプルです。

一方で、既存コードが GA4 の runReport に近いリクエスト形を前提にしている場合は、raw provider proxy を使えます。

const rawGa4Report = await requestGalite("/raw/ga4/proxy", {
  method: "POST",
  body: {
    project_key: projectKey,
    path: "properties/PROPERTY_ID:runReport",
    body: {
      dateRanges: [{ startDate: "28daysAgo", endDate: "today" }],
      metrics: [{ name: "screenPageViews" }],
    },
  },
});

console.dir(rawGa4Report, { depth: null });

新規実装では整理済みエンドポイントを優先し、どうしても provider-native なレスポンスが必要な部分だけ raw proxy を使う、という分け方が扱いやすいです。

運用時の注意点

  • API key はサーバー側に置き、ブラウザへ渡さない
  • key が漏れた場合は GA Lite 側でローテーションする
  • force=1 は手動更新フローなど、本当に再取得したい場面に限定する
  • ダッシュボード用途では短い TTL のキャッシュを挟む
  • エラー時は HTTP status と response body をログに残す
  • 期間指定はアプリ側で選択肢化し、自由入力にしない

まとめ

GA Lite API を使うと、Node.js から GA4 の主要指標をシンプルな Bearer token 認証で取得できます。

プロジェクト一覧で projectKey を確認し、summarytimeseriesdimensionrealtime を用途別に呼び出せば、管理画面、Slack 通知、定期レポート、社内 KPI ダッシュボードなどに組み込みやすくなります。

公式ドキュメント: https://galite.io/api-docs

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?