Google API Client System
The Google API client system provides a robust interface for fetching SEO and analytics data from Google’s suite of APIs. It implements retry logic, error handling, rate limiting, and OAuth 2.0 authentication.Architecture Overview
Core Components
The system is organized into specialized client classes:Authentication Flow
All Google API clients use OAuth 2.0 with the following scopes:createGoogleAuthClient()- Creates OAuth2 client instancerefreshAccessToken(refreshToken)- Refreshes expired tokens
Analytics Client
Class: AnalyticsClient
Handles all Google Analytics 4 (GA4) data retrieval.
Location: src/lib/google/analytics.ts:6
Key Methods
getOrganicTrafficData()
Retrieves comprehensive organic traffic data with period-over-period comparison.
- Calculates previous period dates for comparison
- Fetches current and previous metrics in parallel
- Retrieves landing pages and traffic trends
- Calculates percentage changes
- Returns aggregated
AnalyticsDataobject
getTopLandingPages()
Retrieves top landing pages from organic search traffic.
- Filters by
sessionDefaultChannelGroup = 'Organic Search' - Orders by sessions descending
- Includes bounce rate and engagement metrics
getTrafficSources()
Breaks down traffic by channel (Organic, Direct, Social, etc.).
Location: src/lib/google/analytics.ts:257
Returns:
getConversionData()
Retrieves conversion metrics for ecommerce tracking.
Location: src/lib/google/analytics.ts:310
Property Management
getAccessibleProperties()
Lists all GA4 properties a user has access to.
Location: src/lib/google/analytics.ts:419
Data Flow:
- Lists all Google Analytics accounts
- For each account, lists associated properties
- Extracts property IDs and display names
- Returns formatted array
Search Console Client
Class: SearchConsoleClient
Handles Google Search Console performance data.
Location: src/lib/google/search-console.ts:6
Key Methods
getPerformanceData()
Retrieves comprehensive search performance metrics.
totalClicks- Total search clickstotalImpressions- Total search impressionsaveragePosition- Average ranking positionaverageCTR- Click-through rate percentagetopKeywords- Top 10 performing keywordstopPages- Top 10 landing pagesdailyData- Time-series data for charts
getTopKeywords()
Retrieves top performing search queries.
Location: src/lib/google/search-console.ts:82
getPerformanceComparison()
Compares metrics between two time periods.
Location: src/lib/google/search-console.ts:168
Use Case: Calculating month-over-month or year-over-year changes.
getDailyPerformanceData()
Retrieves time-series data for trend visualization.
Location: src/lib/google/search-console.ts:367
Returns daily metrics sorted by date:
Site Management
getVerifiedSites()
Lists all sites the user has verified in Search Console.
Location: src/lib/google/search-console.ts:253
formatSiteUrl()
Static helper to format domains for Search Console API.
Location: src/lib/google/search-console.ts:310
PageSpeed Client
Class: PageSpeedClient
Handles PageSpeed Insights API integration.
Location: src/lib/google/pagespeed.ts:38
Authentication: Uses API key (not OAuth)
Key Methods
getPageSpeedData()
Retrieves comprehensive performance data for both mobile and desktop.
mobileScore- Mobile performance score (0-100)desktopScore- Desktop performance score (0-100)coreWebVitals- LCP, FID, CLS metricsopportunities- Actionable performance improvements
analyzeCoreWebVitals()
Analyzes Core Web Vitals with Google’s thresholds.
Location: src/lib/google/pagespeed.ts:251
Thresholds:
-
LCP (Largest Contentful Paint)
- Good: ≤ 2500ms
- Needs Improvement: 2501-4000ms
- Poor: > 4000ms
-
FID (First Input Delay)
- Good: ≤ 100ms
- Needs Improvement: 101-300ms
- Poor: > 300ms
-
CLS (Cumulative Layout Shift)
- Good: ≤ 0.1
- Needs Improvement: 0.11-0.25
- Poor: > 0.25
getMultiplePagesSpeeds()
Analyzes multiple pages with rate limit protection.
Location: src/lib/google/pagespeed.ts:341
Features:
- Processes URLs in chunks to avoid rate limiting
- Adds 2-second delay between chunks
- Returns success/error status for each URL
Error Handling
Centralized Error Handling
Location:src/lib/google/error-handling.ts
handleGoogleAPIError()
Classifies and normalizes API errors.
-
401 Unauthorized - Token expired, needs re-authentication
-
429 Rate Limit - Too many requests
-
403 Quota Exceeded - Daily quota exhausted
-
5xx Server Errors - Google API issues
retryWithBackoff()
Exponential backoff retry logic.
Location: src/lib/google/error-handling.ts:72
- Attempt 1: Immediate
- Attempt 2: Wait ~1000ms + random jitter
- Attempt 3: Wait ~2000ms + random jitter
- Attempt 4: Wait ~4000ms + random jitter
Rate Limiting
API Quotas
Configuration:src/lib/google/config.ts:34
Rate Limit Strategy
- Retry on 429 - Wait and retry with exponential backoff
- Chunk Processing - Break large requests into smaller batches
- Delay Between Chunks - Add artificial delays (e.g., 2 seconds)
- Parallel Requests - Fetch independent data sources simultaneously
Integration Points
Report Generation Pipeline
Used by: API routes, background jobs, report generation queueDatabase Models
Client Model: Stores Google API connection statusToken Refresh
Location: Used throughout all client methodsTesting
Validation Methods
Each client includes validation methods for testing connectivity:Performance Considerations
Optimization Strategies
- Parallel Fetching - All clients use
Promise.all()for independent requests - Selective Data - Use
limitparameters to reduce payload size - Caching - Results should be cached at application level
- Timeout Protection - All requests include timeout handling
- Minimal Dimensions - Only request necessary data dimensions
Example: Optimized Report Generation
Common Issues
Token Expiration
Problem: 401 errors after token expiresSolution: Implement automatic refresh before making API calls
Rate Limiting
Problem: 429 errors during bulk operationsSolution: Use chunked processing with delays
Quota Exceeded
Problem: 403 errors when daily quota exhaustedSolution: Track API usage in database, show user remaining quota