{"id":14971034,"url":"https://github.com/7sferry/gatsby-plugin-google-analytics-data-reporting-api","last_synced_at":"2025-10-26T14:30:57.648Z","repository":{"id":107508377,"uuid":"609539380","full_name":"7sferry/gatsby-plugin-google-analytics-data-reporting-api","owner":"7sferry","description":"Google Analytics GA4 Reporting API for GatsbyJS","archived":false,"fork":false,"pushed_at":"2024-10-01T16:10:56.000Z","size":79,"stargazers_count":6,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-31T20:16:08.631Z","etag":null,"topics":["analytics","ga4","gatsbyjs","google","reporting-api"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/7sferry.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-04T13:40:05.000Z","updated_at":"2024-11-27T09:48:48.000Z","dependencies_parsed_at":"2023-09-27T23:13:59.538Z","dependency_job_id":"49317d2f-6918-48ad-af9c-1e2411fce596","html_url":"https://github.com/7sferry/gatsby-plugin-google-analytics-data-reporting-api","commit_stats":{"total_commits":53,"total_committers":4,"mean_commits":13.25,"dds":0.4528301886792453,"last_synced_commit":"f3ef1fa55fa3b12f0ca062ee6028e1deed2fd7d7"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/7sferry","download_url":"https://codeload.github.com/7sferry/gatsby-plugin-google-analytics-data-reporting-api/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238347442,"owners_count":19456935,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["analytics","ga4","gatsbyjs","google","reporting-api"],"created_at":"2024-09-24T13:44:37.496Z","updated_at":"2025-10-26T14:30:57.337Z","avatar_url":"https://github.com/7sferry.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gatsby-plugin-google-analytics-data-reporting-api\n\n## Description\n\nThis is Reporting API plugin to get your page views count from Google Analytics Data API (GA4). Since Universal Analytics is deprecated, so I decide to create one.\n\n## How to install\n\n1. Make sure you already set up Google Analytics 4 and anything related properly;\n2. Enable Google Analytics Data API in your console cloud apis\n   in \"https://console.cloud.google.com/apis/library/analyticsdata.googleapis.com\";\n3. Make sure your Service Account email has \"Viewer\" permissions. It's on Google Analytics page \u003e Admin \u003e Account Access\n   Management \u003e choose the Service Account Email \u003e View user's Account details on Roles and Data Restrictions \u003e Choose\n   your GA 4 property \u003e Set it as \"Viewer\";\n4. run `npm i gatsby-plugin-google-analytics-data-reporting-api`;\n5. add this to your `gatsby-config`:\n\n```js\nplugins: [{\n  //other plugins...\n\n  resolve: `gatsby-plugin-google-analytics-data-reporting-api`,\n  options: {\n    serviceAccountEmail: process.env.ANALYTICS_EMAIL,\n    privateKey: process.env.ANALYTICS_PRIVATE_KEY,\n    property: process.env.ANALYTICS_GA4,\n    startDate: `2020-01-01`,\n    endDate: `yesterday`,\n    limit: 100,\n    metric: `screenPageViews`,\n    regexFilter: `^/page/`,\n    desc: true\n  }\n}]\n```\n\nI recommend you to set the sensitive value above in environment variables, or use \"(dot)env\" in local for security.\n\n## Options\n\n### serviceAccountEmail\n\nrequired. it's your service account email, like xxx@xxx.iam.gserviceaccount.com.\n\n### privateKey\n\nrequired. it's your private key from Google cloud console. download the json, and copy and paste the \"private_key\" here.\nit's start with \"-----BEGIN PRIVATE KEY-----\".\n\n### property\n\nrequired. it's your GA4 property id from Google Analytics Page.\n\n### startDate\n\nrequired since v1.3.0. it's based on Google Analytics date value. Could be '30daysAgo', 'today', 'yesterday', or ISO\ndate format (yyyy-MM-dd) like '2022-12-31'. Default value '365daysAgo'. Google changed its API and for version \u003c v1.3.0\nusing startDate default value will throw error. Since v1.3.0 I encourage to specify your startDate in config or use\ndynamic value like '365daysAgo'.\n\n### endDate\n\nrequired since v1.3.0. it's based on Google Analytics date value. Could be '30daysAgo', 'today', 'yesterday', or ISO\ndate format (yyyy-MM-dd) like '2022-12-31'. Default value 'today'. Since v1.3.0 I encourage to specify your endDate.\n\n### metric\n\noptional. Metric calculation for reporting. Default value is 'screenPageViews' to calculate metric of the number of app\nscreens or web pages your users viewed. Repeated views of a single page or screen are counted. Since v1.1.0 we can use\ncustom metric like 'totalUsers' to calculate based on distinct users, or 'scrolledUsers' to calculate based on total\nusers who scrolled your pages to at least 90% of page.\nVisit \"https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics\" for more info about\nmetric values can be used.\n\n### limit\n\noptional. you can skip this option. it's to limit data fetch from the API. Default value is null which means no limit.\n\n### desc\n\noptional. you can skip this option. it's boolean value to determine you want to order the result by ascending or\ndescending. Default value is true.\n\n### regexFilter\noptional. you can skip this option. it's a regex value to filter page path. for examples, you only want to filter page which starts by \"/page/\", then you can write regex filter value to \"^/page/\".\n\n## Examples of usage\n\nquery the page views like this:\n\n```graphql\nquery AnalyticsPageQuery {\n    allPageViews(sort: { totalCount: DESC }) {\n        nodes {\n            path\n            totalCount\n        }\n    }\n}\n```\n\nthe response would be this:\n\n```json\n{\n  \"data\": {\n    \"allPageViews\": {\n      \"nodes\": [\n        {\n          \"path\": \"/blog/first-blog\",\n          \"totalCount\": 190\n        },\n        {\n          \"path\": \"/blog/second-blog\",\n          \"totalCount\": 55\n        }\n      ]\n    }\n  }\n}\n```\n\n## Using Client Side Reporting Analytics\nBy default, this plugin will fetch analytics in build time. so, any new data can't be fetched until next build. Doing this in runtime on client side would expose our sensitive key.\n\nSince Gatsby 5 (I used v5.13.3), we can create a middleware API on server side. We can use it to get analytics in runtime without exposing sensitive key to client.\n\nTo do this we should create an api inside \"src/api\" directory, for example \"src/api/trending.ts\" (or \"src/api/trending.js\") for api with route: \"/api/trending\" and import getReport from gatsby-plugin-google-analytics-data-reporting-api.\n\n```ts\nimport { GatsbyFunctionRequest, GatsbyFunctionResponse } from \"gatsby\";\nimport {\n  getReport,\n  ReportingPluginOption,\n  TrendingReport,\n} from \"gatsby-plugin-google-analytics-data-reporting-api\";\n\nfunction getTimeToLiveExpiration() {\n   return 24 * 3600;\n}\n\nexport default async function handler(_: GatsbyFunctionRequest, res: GatsbyFunctionResponse) {\n  let ttl = getTimeToLiveExpiration();\n  let opt: ReportingPluginOption = {\n    privateKey: process.env.ANALYTICS_PRIVATE_KEY,\n    property: process.env.ANALYTICS_GA4,\n    serviceAccountEmail: process.env.ANALYTICS_EMAIL,\n    desc: false,\n    endDate: \"yesterday\",\n    limit: 5,\n    metric: \"scrolledUsers\",\n    regexFilter: \"^/blog/\",\n    startDate: \"30daysAgo\",\n  };\n  let reports: TrendingReport[] = await getReport(opt);\n  res.setHeader(\"Cache-Control\", `public, max-age=${ttl}, s-maxage=${ttl + 3600}, stale-while-revalidate=300`).json({\n    nodes: reports,\n  });\n}\n```\nor if using js:\n```js\nimport {\n  getReport\n} from \"gatsby-plugin-google-analytics-data-reporting-api\";\n\nfunction getTimeToLiveExpiration() {\n\treturn 24 * 3600;\n}\n\nexport default async function handler(_, res) {\n  let ttl = getTimeToLiveExpiration();\n  let opt = {\n    privateKey: process.env.ANALYTICS_PRIVATE_KEY,\n    property: process.env.ANALYTICS_GA4,\n    serviceAccountEmail: process.env.ANALYTICS_EMAIL,\n    desc: false,\n    startDate: \"30daysAgo\",\n    endDate: \"yesterday\",\n    limit: 5,\n    metric: \"scrolledUsers\",\n    regexFilter: \"^/blog/\",\n  };\n  let reports = await getReport(opt);\n  res.setHeader(\"Cache-Control\", `public, max-age=${ttl}, stale-while-revalidate=300`).json({\n     reports: reports,\n  });\n}\n```\n\nnotes: better use max-age and set time to live expiration (in seconds) to cache response for better experience.\n\nAnd in your component make an API call to \"/api/trending\" route and render the result:\n```jsx\nimport { useEffect, useState } from \"react\";\n\nconst TopTrending = () =\u003e {\n  const [trendingReports, setTrendingReports] = useState([]);\n  useEffect(() =\u003e {\n    getTopTrendingReports().then(setTrendingReports);\n  }, []);\n\n  return (\n    \u003cul\u003e\n      {trendingReports.map((report) =\u003e {\n        return (\n          \u003cli key={report.path}\u003e\n            \u003csmall className=\"title\"\u003e\n              \u003cLink className=\"text-link\" to={`${report.path}`}\u003e\n                {report.path}\n              \u003c/Link\u003e\n            \u003c/small\u003e\n          \u003c/li\u003e\n        );\n      })}\n    \u003c/ul\u003e\n  );\n};\n\nasync function getTopTrendingReports() {\n  let response = await fetch(\"/api/trending\");\n  if (response.status !== 200) {\n    return [];\n  }\n  const reportNode = await response.json();\n  return reportNode.reports;\n}\n\nexport default TopTrending;\n```\n\n## Changelogs\nSee: https://github.com/7sferry/gatsby-plugin-google-analytics-data-reporting-api/releases\n\n## How to contribute\n\nany ideas or recommendations are welcome.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F7sferry%2Fgatsby-plugin-google-analytics-data-reporting-api/lists"}