DEV Community

Cover image for Which pages get visits from ChatGPT and Gemini? A GA4 Data API script in Node.js
Ed Grows
Ed Grows

Posted on

Which pages get visits from ChatGPT and Gemini? A GA4 Data API script in Node.js

To see which pages get visits from AI assistants, query the GA4 Data API for sessions where sessionMedium is ai-assistant, grouped by landingPage and sessionSource. GA4 sets that medium when the referrer matches its list of AI assistants such as ChatGPT, Gemini, Deepseek, Copilot or Grok. The script below prints the top landing pages, their sources and engagement rate.

TL;DR: one runReport call, filter on medium ai-assistant, group by landing page. Google's own AI Overviews and AI Mode are not in this channel; they stay in Organic Search.

What is the GA4 "AI Assistant" channel?

GA4's default channel group has an AI Assistant channel for users who arrive from sources like ChatGPT, Gemini, Deepseek, Copilot or Grok. The rule behind it: the medium is set to ai-assistant (and the campaign to (ai-assistant)) when the referrer matches GA4's list of AI assistants. The same page notes that the channel excludes Google's AI Overviews and AI Mode (GA4 default channel group).

That gives you a clean filter for the API: sessionMedium = ai-assistant.

Where the visit came from Where it shows in GA4
a link in a ChatGPT, Gemini, Copilot answer AI Assistant channel, medium ai-assistant
Google AI Overviews or AI Mode Organic Search
an assistant that sends no referrer usually Direct

Setup

  1. Create a service account in Google Cloud and enable the Google Analytics Data API.
  2. In GA4, add the service account email as a Viewer on the property.
  3. Install the client and point it at the key file:
npm install @google-analytics/data
export GOOGLE_APPLICATION_CREDENTIALS=./service-account.json
Enter fullscreen mode Exit fullscreen mode

The dimension names used below (landingPage, sessionSource, sessionMedium) are from the Data API schema.

The script

// ai-landing-pages.mjs: landing pages that get sessions from AI assistants (GA4 Data API)
// npm install @google-analytics/data
// export GOOGLE_APPLICATION_CREDENTIALS=./service-account.json
import analyticsData from '@google-analytics/data'; // CommonJS package: default import works in every Node version

const { BetaAnalyticsDataClient } = analyticsData;

const propertyId = process.argv[2];
const days = Number(process.argv[3] ?? 90);
if (!propertyId) {
  console.error('usage: node ai-landing-pages.mjs <GA4 property id> [days=90]');
  process.exit(1);
}

const client = new BetaAnalyticsDataClient();

const [response] = await client.runReport({
  property: `properties/${propertyId}`,
  dateRanges: [{ startDate: `${days}daysAgo`, endDate: 'yesterday' }],
  dimensions: [{ name: 'landingPage' }, { name: 'sessionSource' }],
  metrics: [{ name: 'sessions' }, { name: 'engagedSessions' }],
  dimensionFilter: {
    filter: {
      fieldName: 'sessionMedium',
      stringFilter: { matchType: 'EXACT', value: 'ai-assistant' },
    },
  },
  orderBys: [{ metric: { metricName: 'sessions' }, desc: true }],
  limit: 1000,
});

// Group by landing page, keep the sources as a short list
const pages = new Map();
for (const row of response.rows ?? []) {
  const [page, source] = row.dimensionValues.map((d) => d.value);
  const [sessions, engaged] = row.metricValues.map((m) => Number(m.value));
  const p = pages.get(page) ?? { page, sessions: 0, engaged: 0, sources: {} };
  p.sessions += sessions;
  p.engaged += engaged;
  p.sources[source] = (p.sources[source] ?? 0) + sessions;
  pages.set(page, p);
}

const rows = [...pages.values()]
  .sort((a, b) => b.sessions - a.sessions)
  .slice(0, 25)
  .map((p) => ({
    page: p.page,
    sessions: p.sessions,
    engagement: p.sessions ? `${Math.round((100 * p.engaged) / p.sessions)}%` : '-',
    sources: Object.entries(p.sources).sort((a, b) => b[1] - a[1]).map(([s, n]) => `${s} ${n}`).join(', '),
  }));

console.table(rows);
console.log(`${pages.size} landing pages with AI assistant sessions in the last ${days} days`);
Enter fullscreen mode Exit fullscreen mode

Run it with your numeric property ID:

node ai-landing-pages.mjs 123456789 90
Enter fullscreen mode Exit fullscreen mode

The output is a table with the landing page, total AI assistant sessions, the share of engaged sessions and the sources, for example chatgpt.com 41, gemini.google.com 6 (illustrative, your sources will differ).

How to read the result

  • Pages at the top are the ones assistants link to. They are worth keeping accurate and up to date first, because people arrive there with a specific question.
  • A low engagement rate on a page with many AI sessions usually means the answer promised something the page does not deliver quickly. Put the direct answer near the top.
  • Pages missing from the list that rank well in Search may simply not be cited, or the assistant may not pass a referrer. Absence here is not proof of anything.

Limits worth knowing

  • Visits without a referrer land in Direct, so the channel undercounts.
  • Google's AI Overviews and AI Mode are counted in Organic Search and in Search Console's Performance report, not here.
  • GA4's list of AI assistants is maintained by Google. A new assistant may show up as Referral until the list is updated, so also check sessionSource values under Referral now and then.

Ideas to extend it

  1. Add date as a dimension to see the trend per week.
  2. Compare the same pages' Organic Search sessions to see where AI visits are a large share.
  3. Write the rows to a CSV and keep one file per month.

If you want a broader picture than one channel report, this overview from citelity covers the other places AI visibility shows up.

FAQ

Do I need GA4 360 for this?
No. The Data API works with standard GA4 properties.

Why use medium instead of the channel group?
Both work. Filtering on sessionMedium is explicit and does not depend on how the channel group is displayed in your property.

Does this include Perplexity?
If GA4 recognises the referrer as an AI assistant, yes. Check sessionSource values to see what is being classified.

How far back can I go?
As far as your GA4 data retention and the date the channel was introduced allow.

Top comments (0)