kanmi-ga4-cli
v1.0.1
Published
CLI tool for Google Analytics 4 data retrieval with OAuth authentication
Maintainers
Readme
kanmi-ga4-cli - Google Analytics 4 Data Retrieval Tool
A powerful command-line interface for retrieving Google Analytics 4 data with OAuth authentication, multiple output formats, and comprehensive reporting capabilities.
✨ Features
- 🔐 OAuth2 Authentication - Secure authentication with Google Analytics
- 📊 Multiple Report Types - Custom reports, comparisons, top events, and pages
- 📁 Multiple Output Formats - Table, JSON, Markdown, and CSV
- 🔄 Date Range Comparisons - Compare current vs previous periods
- 💾 File Export - Save reports to files
- 🎯 Flexible Metrics & Dimensions - Use any GA4 metric/dimension combination
📦 Installation
Prerequisites
- Node.js 16.0.0 or higher
- A Google Cloud Project with Analytics API enabled
- GA4 property access
Install Dependencies
npm installBuild the Project
npm run buildInstall Globally (Optional)
npm link🔧 Setup
1. Create Google Cloud Project & Enable APIs
- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable the Google Analytics Data API
- Enable the Google Analytics Admin API (optional, for property listing)
2. Create OAuth2 Credentials
- Go to APIs & Services > Credentials
- Click Create Credentials > OAuth 2.0 Client ID
- Choose Desktop Application (important for CLI tools)
- Download the credentials JSON file
- Note the
client_idandclient_secretvalues
3. Set Environment Variables
You can use the setup script:
npm run setupOr create a .env file manually in the project root:
CLIENT_ID=your-google-client-id
CLIENT_SECRET=your-google-client-secret4. Find Your GA4 Property ID
Your GA4 property ID is the numeric ID found in:
- Google Analytics > Admin > Property > Property Details
- URL:
https://analytics.google.com/analytics/web/#/pXXXXXXXXX/(the X's are your property ID)
🚀 Usage
Authentication
On first run, the CLI will open your browser for OAuth authentication. The token will be saved to ~/.ga4-cli/token.json for future use.
Commands
📊 Custom Reports
Generate custom reports with any combination of metrics and dimensions:
ga4-cli report --property=123456789 --metrics=users,sessions --dimensions=country,deviceCategoryOptions:
-p, --property <propertyId>- GA4 property ID (required)-m, --metrics <metrics>- Comma-separated metrics (required)-d, --dimensions <dimensions>- Comma-separated dimensions (optional)-s, --start-date <date>- Start date (YYYY-MM-DD, default: 7 days ago)-e, --end-date <date>- End date (YYYY-MM-DD, default: today)-f, --format <format>- Output format: table|json|markdown|csv (default: table)-o, --output <file>- Save to file (optional)-l, --limit <number>- Maximum rows (default: 100)
🔄 Date Range Comparisons
Compare metrics between two time periods:
ga4-cli compare --property=123456789 --metrics=users,sessions --dimensions=pagePathOptions:
- Same as report command, plus:
--current-start <date>- Current period start date--current-end <date>- Current period end date--previous-start <date>- Previous period start date--previous-end <date>- Previous period end date
Note: If dates not specified, defaults to this week vs last week
🎯 Top Events
Get your most triggered events:
ga4-cli events --property=123456789 --format=markdown --output=events.mdOptions:
-p, --property <propertyId>- GA4 property ID (required)-s, --start-date <date>- Start date (default: 7 days ago)-e, --end-date <date>- End date (default: today)-f, --format <format>- Output format (default: table)-o, --output <file>- Save to file (optional)-l, --limit <number>- Maximum rows (default: 20)
📄 Top Pages
Get your most visited pages:
ga4-cli pages --property=123456789 --format=jsonOptions:
- Same as events command
📊 Available Metrics & Dimensions
Popular Metrics
users- Total userssessions- Total sessionsscreenPageViews- Page viewseventCount- Event countbounceRate- Bounce ratesessionDuration- Session durationengagementRate- Engagement rateconversions- ConversionstotalRevenue- Total revenue
Popular Dimensions
country- Countryregion- Regioncity- CitypagePath- Page pathpageTitle- Page titleeventName- Event namesource- Traffic sourcemedium- Traffic mediumcampaign- Campaign namedeviceCategory- Device categoryoperatingSystem- Operating systembrowser- Browserdate- Datehour- Hourminute- Minute
📋 Example Commands
Basic Usage
# Get users by country (last 7 days)
ga4-cli report -p 123456789 -m users -d country
# Get page views for specific pages
ga4-cli report -p 123456789 -m screenPageViews -d pagePath -s 2024-01-01 -e 2024-01-31
# Export top events to markdown
ga4-cli events -p 123456789 -f markdown -o events.md
# Compare this week vs last week
ga4-cli compare -p 123456789 -m users,sessions -d deviceCategoryAdvanced Usage
# Custom date range comparison
ga4-cli compare -p 123456789 -m users \
--current-start 2024-01-01 --current-end 2024-01-31 \
--previous-start 2023-01-01 --previous-end 2023-01-31
# Multiple metrics and dimensions
ga4-cli report -p 123456789 \
-m users,sessions,screenPageViews,eventCount \
-d country,deviceCategory,source,medium \
-l 50 -f json -o report.json
# Top 100 pages with sessions data
ga4-cli pages -p 123456789 -l 100 -f csv -o pages.csv🔍 Output Formats
Table Format
┌──────────────┬─────────┬──────────┐
│ country │ users │ sessions │
├──────────────┼─────────┼──────────┤
│ United States│ 1,234 │ 1,456 │
│ Canada │ 567 │ 678 │
└──────────────┴─────────┴──────────┘JSON Format
{
"summary": {
"totalRows": 2,
"dimensionHeaders": ["country"],
"metricHeaders": ["users", "sessions"]
},
"data": [
{
"country": "United States",
"users": "1234",
"sessions": "1456"
}
]
}Markdown Format
# GA4 Report Results
Total rows: 2
| country | users | sessions |
| --- | --- | --- |
| United States | 1,234 | 1,456 |
| Canada | 567 | 678 |CSV Format
country,users,sessions
United States,1234,1456
Canada,567,678🚨 Troubleshooting
Authentication Issues
Error: "Authentication failed"
- Ensure
CLIENT_IDandCLIENT_SECRETare correctly set in.env - Check that the Google Analytics Data API is enabled in your project
- Verify your OAuth2 credentials are for a "Desktop Application"
Error: "Token invalid"
- Delete
~/.ga4-cli/token.jsonand re-authenticate - Run
ga4-cli logoutto revoke tokens
API Issues
Error: "Property not found"
- Verify the property ID is correct
- Ensure you have access to the GA4 property
- Check that the property ID is numeric (not the measurement ID starting with "G-")
Error: "Invalid metric/dimension"
- Check the metric/dimension names for typos
- Refer to the GA4 Dimensions & Metrics Explorer
Common Issues
No data returned
- Check your date range
- Verify the property has data for the specified period
- Some metrics may not be available for certain dimensions
📚 Development
Project Structure
src/
├── commands/
│ ├── report.ts # Custom report command
│ ├── compare.ts # Date comparison command
│ ├── events.ts # Top events command
│ └── pages.ts # Top pages command
├── utils/
│ ├── auth.ts # OAuth2 authentication
│ ├── ga4.ts # GA4 API wrapper
│ └── formatter.ts # Output formatting
└── index.ts # CLI entry pointBuild & Test
# Build the project
npm run build
# Run in development mode
npm run dev
# Test a command
npm run dev -- report -p 123456789 -m users -d country📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📧 Support
For issues and questions, please open an issue on GitHub.
Built with ❤️ for the Google Analytics community
