Using Google Analytics Data API in Next.js
June 5, 2025
~3 min read
Next.jsGoogle AnalyticsData APITypeScript
Introduction
In this post, I'll share how I implemented the Google Analytics Data API in my Next.js portfolio website to fetch and display visitor analytics data.
Setting Up Google Analytics Data API
First, we need to set up the Google Analytics Data API and get the necessary credentials. Here's a step-by-step guide:
1. Set Up Google Analytics Data API
- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable the Google Analytics Data API for your project
- Go to "APIs & Services" → "Credentials"
- Click "Create Credentials" → "Service Account"
- Fill in the service account details and click "Create"
- Click on the created service account → "Keys" → "Add Key" → "Create new key"
- Choose JSON format and download the key file
- Add the service account email to your Google Analytics property with "Viewer" permissions
2. Configure Environment Variables
Add the following variables to your .env.local file:
bash
1# Google Analytics Configuration
2NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID=XXXXXXXXXX # Your GA4 Property ID
3NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com # From service account JSON
4NEXT_PUBLIC_GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
5...
6-----END PRIVATE KEY-----
7" # From service account JSON3. Install Required Dependencies
Install the necessary packages for Google Analytics Data API integration:
bash
1npm install @google-analytics/data
2# or
3yarn add @google-analytics/data
4# or
5pnpm add @google-analytics/data4. Create Analytics Client
Create a client using the Google Analytics Data API:
typescript
1import { BetaAnalyticsDataClient } from "@google-analytics/data";
2
3const { private_key } = JSON.parse(
4 process.env.NEXT_PUBLIC_GOOGLE_PRIVATE_KEY || "{ private_key: null }"
5);
6
7export const analyticsDataClient = new BetaAnalyticsDataClient({
8 credentials: {
9 client_email: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL!,
10 private_key: private_key,
11 },
12});5. Create API Route
Create an API route to fetch analytics data securely from the server side:
typescript
1import { NextResponse } from "next/server";
2import { analyticsDataClient } from "@/lib/google/client";
3
4export async function GET() {
5 try {
6 const propertyId = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID;
7 if (!propertyId) {
8 return NextResponse.json(
9 { error: "Google Analytics Property ID is not configured" },
10 { status: 500 }
11 );
12 }
13
14 const [response] = await analyticsDataClient.runReport({
15 property: `properties/${propertyId}`,
16 dateRanges: [
17 {
18 startDate: "2024-06-30",
19 endDate: "today",
20 },
21 ],
22 metrics: [{ name: "totalUsers" }],
23 });
24
25 const metrics = response.rows?.[0]?.metricValues || [];
26 const visitorCount = Number(metrics[0]?.value) || 0;
27
28 return NextResponse.json({ visitorCount });
29 } catch (error) {
30 console.error("Error fetching analytics data:", error);
31 return NextResponse.json(
32 { error: "Failed to fetch analytics data" },
33 { status: 500 }
34 );
35 }
36}6. Create Visitor Count Component
Create a component to display the visitor count in the UI:
tsx
1import { useEffect, useState } from "react";
2import { getUniqueVisitors } from "@/utils/analytics";
3import { motion } from "framer-motion";
4import { Users } from "lucide-react";
5
6export default function VisitorCount() {
7 const [visitorCount, setVisitorCount] = useState<number>(0);
8 const [loading, setLoading] = useState(true);
9
10 useEffect(() => {
11 const fetchVisitors = async () => {
12 try {
13 const count = await getUniqueVisitors();
14 setVisitorCount(count);
15 } catch (error) {
16 console.error("Failed to fetch visitor count:", error);
17 } finally {
18 setLoading(false);
19 }
20 };
21
22 fetchVisitors();
23 // Refresh count every 5 minutes
24 const interval = setInterval(fetchVisitors, 5 * 60 * 1000);
25 return () => clearInterval(interval);
26 }, []);
27
28 if (loading) {
29 return (
30 <div className="flex items-center gap-2 px-3 py-1.5 text-sm text-muted-foreground">
31 <Users className="h-4 w-4" />
32 <span>Loading...</span>
33 </div>
34 );
35 }
36
37 return (
38 <motion.div
39 initial={{ opacity: 0, y: -10 }}
40 animate={{ opacity: 1, y: 0 }}
41 className="flex items-center gap-2 px-3 py-1.5 text-sm text-muted-foreground"
42 >
43 <Users className="h-4 w-4" />
44 <span>{visitorCount.toLocaleString()} visitors</span>
45 </motion.div>
46 );
47}Best Practices
When implementing Google Analytics Data API in a Next.js application, consider these best practices:
- Use environment variables for sensitive credentials
- Implement server-side data fetching for better security
- Add proper error handling and loading states
- Consider rate limiting and caching for API calls
- Follow privacy regulations and add cookie consent if needed
Conclusion
Implementing Google Analytics Data API in a Next.js application provides valuable insights into user behavior and website performance. The combination of server-side data fetching and proper error handling offers a robust solution for analytics integration.