Google Analytics 4 (GA4) Setup and Configuration
Why GA4 Matters
Key Changes from Universal Analytics (UA):
- Event-based tracking (not session-based)
- Better cross-device tracking
- AI-powered insights
- Privacy-focused
- Better integration with other tools
What You Track:
- Organic traffic volume
- User behavior on site
- Conversion funnels
- Revenue (if applicable)
- Content performance
- User demographics
GA4 Setup Steps
Step 1: Create Google Analytics 4 Property
- Go to analytics.google.com
- Click "Admin"
- Select account
- Click "Create Property"
- Choose GA4
- Configure basic settings:
- Property name
- Reporting timezone
- Currency (if e-commerce)
- Industry category
Step 2: Add Tracking Code to Website
Option A: Google Tag Manager (Recommended)
<!-- Add to <head> -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
Option B: Direct Implementation
In Next.js:
// app/layout.tsx
import Script from 'next/script'
export default function RootLayout() {
return (
<html>
<head>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX`}
/>
<Script
id="google-analytics"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
`,
}}
/>
</head>
<body>{/* content */}</body>
</html>
)
}
Step 3: Verify Tracking is Working
- GA4 → Real-time report
- Visit your website
- Should see yourself in real-time users
- If not, check:
- Correct tracking ID
- Script properly placed
- No ad blockers
- No "Do Not Track" enabled
GA4 Key Configuration
Create Data Streams:
-
Web Stream (for website)
- Settings → Data streams
- Create web stream
- Enter website URL
- Get tracking ID (G-XXXXXXXXXX)
-
Configure Enhanced Measurement:
- Automatically track: page views, scrolls, clicks, searches, video engagement
- Settings → Data streams → Edit → Enhanced measurement
- Toggle features on/off
Create Custom Events:
// Track when user clicks CTA button
gtag('event', 'cta_click', {
'button_name': 'contact_button',
'location': 'hero_section'
});
// Track form submissions
gtag('event', 'form_submit', {
'form_name': 'contact_form',
'form_type': 'inquiry'
});
// Track content engagement
gtag('event', 'scroll_depth', {
'scroll_percentage': 75,
'page_title': 'React Guide'
});
GA4 Navigation
Key Reports:
-
Home Dashboard
- Users overview
- Real-time activity
- Trending insights
-
Reports:
- User acquisition (where do users come from?)
- User engagement (how do they behave?)
- Monetization (revenue if applicable)
- Retention (do they come back?)
- Paths (user journey analysis)
-
Explore (Advanced):
- Custom analysis
- Funnels
- Cohort analysis
- User segments
Google Search Console Setup and Monitoring
What is Google Search Console?
Purpose:
- Google's way of communicating with you
- Shows how Google sees your site
- Real search data (impressions, clicks, rankings)
- Issues Google finds
- Manual actions/penalties
Value Over GA4:
- Real Google data (not sampling)
- Keyword rankings and CTR
- Crawl errors and issues
- External links to your site
- Search appearance
GSC Setup
Step 1: Verify Ownership
Go to search.google.com/search-console/about
- Add property
- Enter domain
- Verify ownership (multiple methods):
- HTML file upload
- HTML tag
- Google Analytics
- Google Tag Manager
- DNS record
Recommended: Use Google Analytics or Google Tag Manager (already installed)
Step 2: Submit Sitemap
- GSC → Sitemaps
- Click "Add new sitemap"
- Enter URL: https://harsh-softwaredev.vercel.app/sitemap.xml
- Submit
Monitor:
- Coverage (pages indexed)
- Status (any issues?)
- Indexing progress
Step 3: Request Indexing
For new pages:
- GSC → URL Inspection
- Enter page URL
- Click "Request indexing"
- Google will crawl within hours
GSC Key Reports
1. Performance Report
Shows:
- Clicks from Google search
- Impressions (page showed in results)
- Average position
- Click-through rate (CTR)
Filters:
- By query (keywords)
- By page (which pages rank)
- By country
- By device
- By search type
What to Look For:
- Which keywords drive clicks?
- Which positions generate clicks?
- How's CTR? (Can you improve title/description?)
- Opportunities to rank for new keywords
2. Coverage Report
Shows:
- Valid pages (indexed successfully)
- Excluded pages (intentionally not indexed)
- Errors (pages not indexed, problems)
- Valid with warnings
Common Issues:
- Soft 404s (page not found but returns 200)
- Redirect errors
- Crawl anomalies
- Access denied
3. Core Web Vitals Report
Shows:
- LCP, FID, CLS performance
- Good/needs improvement/poor
- Affected pages
- Trends over time
Action:
- Identify pages with poor metrics
- Run PageSpeed Insights
- Fix performance issues
4. Mobile Usability Report
Shows:
- Mobile-specific issues
- Clickable elements too close
- Text too small
- Viewport configuration
Action:
- Fix mobile issues
- Test on real devices
- Revalidate in GSC
5. Links Report
Shows:
- Top linked pages (internal)
- Top linking sites (external)
- Link counts
- Trends
Use For:
- Understanding internal link structure
- Finding backlink opportunities
- Monitoring competitor links
Google Tag Manager (GTM) Implementation
What is GTM?
Definition:
- Container that holds all tracking codes
- Single place to manage pixels, tags, events
- Change tracking without code modifications
- Easier to manage multiple tools
Benefits:
- ✅ No code changes needed
- ✅ Version control for tags
- ✅ Easier debugging
- ✅ Central management
- ✅ Easier testing
GTM Setup
Step 1: Create GTM Account
- Go to tagmanager.google.com
- Create account
- Create container (choose "Web")
- Install GTM code (two pieces)
Step 2: Install GTM Code
<!-- Install in <head> -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXXXX');</script>
<!-- Install in <body> (top) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
Creating Tags in GTM
Example 1: Google Analytics Event Tag
- Create new tag
- Tag type: Google Analytics: GA4 Event
- Event name: form_submit
- Trigger: Form Submission
- Save and publish
Example 2: Conversion Tracking Tag
- Create new tag
- Type: Google Ads Conversion Tracking
- Conversion ID and Label from Google Ads
- Trigger: When purchase completed
- Save
Creating Triggers
Trigger Types:
- Page view (every page load)
- Click (when link/button clicked)
- Form submission
- Scroll depth
- Custom event
- Page view - DOM ready
Example Trigger:
Trigger Name: Contact Form Submit
Trigger Type: Form Submission
This trigger fires on: Some Forms
Form ID equals: contact-form
Conversion Tracking and Goals
What are Conversions?
Definition:
- Desired user action on your site
- Different for each business type
Examples for harsh-softwaredev.vercel.app:
- Contact form submission
- Email signup
- Lead magnet download
- Product purchase
- Demo booking
- Phone call
- File download
Setting Up Conversions in GA4
Method 1: Auto-tracked Conversions
GA4 automatically tracks:
- E-commerce purchases
- Search queries
- Form submissions
- Video engagement
- File downloads
Enable in: GA4 → Admin → Events → Create event
Method 2: Custom Conversion Events
// Track contact form submission
gtag('event', 'generate_lead', {
'value': 50,
'currency': 'USD',
'lead_type': 'contact_form'
});
// Track email signup
gtag('event', 'sign_up', {
'method': 'email'
});
// Track demo booking
gtag('event', 'book_demo', {
'value': 0,
'event_category': 'engagement'
});
Method 3: Marking Conversions (GA4 Admin)
- Go to GA4 → Admin
- Events section
- Find event to mark as conversion
- Toggle "Mark as conversion"
Conversion Goals for harsh-softwaredev.vercel.app
Tier 1: High-Value Goals
- Contact form submission (Lead)
- Consultation booked (Demo)
- Project quote request
Tier 2: Mid-Value Goals
- Email newsletter signup
- Course enrollment
- Resource download
Tier 3: Low-Value Goals (Engagement)
- Blog subscription
- Social media follow
- Comment on post
- Share article
Event Tracking for User Behavior
Key Events to Track
Page Engagement:
// Scroll depth
gtag('event', 'scroll', {
'depth_threshold': 75
});
// Time on page
gtag('event', 'page_time', {
'time_seconds': 180
});
// Video engagement
gtag('event', 'video_start', {
'video_title': 'React Tutorial',
'video_length': 600
});
Content Interaction:
// Download resource
gtag('event', 'download', {
'file_name': 'react-guide.pdf',
'file_type': 'pdf'
});
// Code copy (if you have code examples)
gtag('event', 'code_copy', {
'language': 'javascript',
'code_snippet': 'useState_example'
});
// Link click
gtag('event', 'link_click', {
'link_url': 'https://example.com',
'link_text': 'Learn More'
});
Commerce Events (if applicable):
// View product
gtag('event', 'view_item', {
'items': [{
'id': 'course-001',
'name': 'React Mastery Course',
'price': 99
}]
});
// Add to cart
gtag('event', 'add_to_cart', {
'value': 99,
'currency': 'USD',
'items': [{ 'id': 'course-001' }]
});
// Purchase
gtag('event', 'purchase', {
'transaction_id': 'TX-001',
'value': 99,
'currency': 'USD',
'items': [{ 'id': 'course-001' }]
});
Implementing Event Tracking in React
Custom Hook for Tracking:
// hooks/useTrackEvent.ts
import { useCallback } from 'react'
export function useTrackEvent() {
return useCallback((eventName: string, eventData?: Record<string, any>) => {
if (typeof window !== 'undefined' && window.gtag) {
window.gtag('event', eventName, eventData)
}
}, [])
}
// Usage
import { useTrackEvent } from '@/hooks/useTrackEvent'
export function ContactForm() {
const trackEvent = useTrackEvent()
const handleSubmit = async (data) => {
// Submit form
await submitForm(data)
// Track conversion
trackEvent('generate_lead', {
'lead_type': 'contact_form',
'value': 50
})
}
return <form onSubmit={handleSubmit}>...</form>
}
E-commerce Tracking (If Applicable)
Setup E-commerce Tracking
GA4 Admin:
- Data collection → Ecommerce
- Toggle on ecommerce features
- Configure product and category names
Tracking Events
Complete Purchase Flow:
// 1. User views product
gtag('event', 'view_item', {
'value': 99.99,
'currency': 'USD',
'items': [{
'item_id': 'PROD123',
'item_name': 'Premium Course',
'item_category': 'Courses',
'price': 99.99
}]
});
// 2. User adds to cart
gtag('event', 'add_to_cart', {
'value': 99.99,
'currency': 'USD',
'items': [{
'item_id': 'PROD123',
'item_name': 'Premium Course',
'quantity': 1
}]
});
// 3. User begins checkout
gtag('event', 'begin_checkout', {
'value': 99.99,
'currency': 'USD',
'items': [{ 'item_id': 'PROD123' }]
});
// 4. User completes purchase
gtag('event', 'purchase', {
'transaction_id': 'T12345',
'value': 99.99,
'currency': 'USD',
'tax': 9.99,
'shipping': 0,
'items': [{
'item_id': 'PROD123',
'item_name': 'Premium Course',
'quantity': 1,
'price': 99.99
}]
});