Google Analytics is one of the most powerful tools for analyzing websites and understanding user behavior. With the release of Google Analytics 4 (GA4), the platform became even more flexible and feature-rich. In this article, we’ll cover all aspects of setting up and using GA4 for maximum effectiveness.
The importance of web analytics
Web analytics is a critical tool for understanding how well a website is performing. Properly configured analytics helps you:
- Understand user behavior
- Track conversions and goals
- Optimize the user experience
- Make informed decisions about the development of your website
- Measure the ROI of marketing campaigns
Setting up Google Analytics 4
Creating an account and property
-
Go to Google Analytics:
- Open analytics.google.com
- Sign in to your Google account
-
Create an account:
CodeYAML Название аккаунта: Ваша компания Название ресурса: Ваш сайт URL: https://yoursite.com Отрасль: Выберите подходящую Часовой пояс: Ваш часовой пояс -
Configure a data stream:
- Select the platform (Web)
- Enter your website URL
- Configure enhanced measurement
Installing the tracking code
Basic GA4 code:
<!-- Google tag (gtag.js) -->
<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>Installation in HTML:
<!DOCTYPE html>
<html>
<head>
<title>Ваш сайт</title>
<!-- Google tag (gtag.js) -->
<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>
</head>
<body>
<!-- Содержимое сайта -->
</body>
</html>Installation in React:
// App.js
import { useEffect } from 'react';
function App() {
useEffect(() => {
// Загрузка Google Analytics
const script1 = document.createElement('script');
script1.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
script1.async = true;
document.head.appendChild(script1);
const script2 = document.createElement('script');
script2.innerHTML = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
`;
document.head.appendChild(script2);
}, []);
return (
<div className="App">
{/* Содержимое приложения */}
</div>
);
}Installation in Next.js:
// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
// Инициализация GA4
const handleRouteChange = (url) => {
gtag('config', 'G-XXXXXXXXXX', {
page_path: url,
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
}Event tracking
Basic events
Tracking clicks:
// Отслеживание клика по кнопке
document.getElementById('cta-button').addEventListener('click', function() {
gtag('event', 'click', {
event_category: 'engagement',
event_label: 'cta_button',
value: 1
});
});Tracking forms:
// Отслеживание отправки формы
document.getElementById('contact-form').addEventListener('submit', function(e) {
gtag('event', 'form_submit', {
event_category: 'engagement',
event_label: 'contact_form',
form_name: 'contact'
});
});Tracking scrolls:
// Отслеживание глубины скролла
let maxScroll = 0;
window.addEventListener('scroll', function() {
const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
if (scrollPercent > maxScroll) {
maxScroll = scrollPercent;
if (maxScroll >= 25 && maxScroll < 50) {
gtag('event', 'scroll', {
event_category: 'engagement',
event_label: '25_percent'
});
} else if (maxScroll >= 50 && maxScroll < 75) {
gtag('event', 'scroll', {
event_category: 'engagement',
event_label: '50_percent'
});
} else if (maxScroll >= 75) {
gtag('event', 'scroll', {
event_category: 'engagement',
event_label: '75_percent'
});
}
}
});Custom events
Tracking time on page:
// Отслеживание времени на странице
let startTime = Date.now();
window.addEventListener('beforeunload', function() {
const timeOnPage = Math.round((Date.now() - startTime) / 1000);
gtag('event', 'timing_complete', {
event_category: 'engagement',
event_label: 'time_on_page',
value: timeOnPage
});
});Tracking videos:
// Отслеживание воспроизведения видео
const video = document.getElementById('video');
video.addEventListener('play', function() {
gtag('event', 'video_start', {
event_category: 'engagement',
event_label: 'main_video'
});
});
video.addEventListener('pause', function() {
gtag('event', 'video_pause', {
event_category: 'engagement',
event_label: 'main_video'
});
});
video.addEventListener('ended', function() {
gtag('event', 'video_complete', {
event_category: 'engagement',
event_label: 'main_video'
});
});Setting up goals and conversions
Creating goals
-
Go to settings:
- Admin → Property → Goals
-
Create a new goal:
CodeText Название: Заявка с сайта Тип: Событие Условие: event_name equals form_submit -
Configure a funnel:
CodeText Шаг 1: Просмотр страницы контактов Шаг 2: Заполнение формы Шаг 3: Отправка формы
Conversion tracking
Tracking purchases:
// Отслеживание покупки
function trackPurchase(orderId, value, currency = 'RUB') {
gtag('event', 'purchase', {
transaction_id: orderId,
value: value,
currency: currency,
items: [
{
item_id: 'product_123',
item_name: 'Название продукта',
price: value,
quantity: 1
}
]
});
}Tracking add-to-cart actions:
// Отслеживание добавления в корзину
function trackAddToCart(productId, productName, price) {
gtag('event', 'add_to_cart', {
currency: 'RUB',
value: price,
items: [
{
item_id: productId,
item_name: productName,
price: price,
quantity: 1
}
]
});
}Advanced setup
Custom parameters
Configuring custom parameters:
// Отправка пользовательских параметров
gtag('config', 'G-XXXXXXXXXX', {
custom_map: {
'custom_parameter_1': 'user_type',
'custom_parameter_2': 'subscription_level'
}
});
// Использование пользовательских параметров
gtag('event', 'page_view', {
user_type: 'premium',
subscription_level: 'pro'
});Tracking custom events:
// Отслеживание пользовательских событий
function trackCustomEvent(eventName, parameters = {}) {
gtag('event', eventName, {
event_category: 'custom',
...parameters
});
}
// Пример использования
trackCustomEvent('feature_used', {
feature_name: 'calculator',
user_segment: 'business'
});Enhanced Ecommerce
Configuring Enhanced Ecommerce:
// Включение Enhanced Ecommerce
gtag('config', 'G-XXXXXXXXXX', {
'enhanced_ecommerce': true
});
// Отслеживание просмотра продукта
function trackProductView(productId, productName, price, category) {
gtag('event', 'view_item', {
currency: 'RUB',
value: price,
items: [
{
item_id: productId,
item_name: productName,
price: price,
item_category: category
}
]
});
}
// Отслеживание начала оформления покупки
function trackBeginCheckout(items, totalValue) {
gtag('event', 'begin_checkout', {
currency: 'RUB',
value: totalValue,
items: items
});
}Data analysis
Key reports
“Audience” report:
- Active users
- New and returning users
- Demographic data
- Geographic location
“Acquisition” report:
- Traffic sources
- Acquisition channels
- Campaign performance
- UTM tags
“Behavior” report:
- Popular pages
- Time on site
- Pages per session
- Bounce rate
“Conversions” report:
- Goal completions
- Conversion funnel
- Channel performance
- Campaign ROI
Custom reports
Creating a custom report:
- Go to “Custom reports”
- Create a new report
- Select metrics and dimensions
- Configure filters
Example of a custom report:
Название: Эффективность страниц
Метрики: Просмотры страниц, Время на странице, Отказы
Измерения: URL страницы, Источник трафика
Фильтры: Только органический трафикIntegration with other tools
Google Ads
Linking to Google Ads:
- Settings → Linked accounts
- Select a Google Ads account
- Confirm the link
Conversion tracking:
// Отслеживание конверсии для Google Ads
gtag('event', 'conversion', {
send_to: 'AW-CONVERSION_ID/CONVERSION_LABEL',
value: 100,
currency: 'RUB',
transaction_id: 'order_123'
});Google Search Console
Linking to Search Console:
- Settings → Linked accounts
- Select Search Console
- Confirm access permissions
Google Tag Manager
Installation through GTM:
<!-- Google Tag Manager -->
<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-XXXXXXX');</script>
<!-- End Google Tag Manager -->Optimization and A/B testing
Setting up experiments
Creating an experiment:
- Settings → Experiments
- Create a new experiment
- Configure variants
- Define goals
Tracking experiments:
// Отслеживание участия в эксперименте
gtag('event', 'experiment_impression', {
experiment_id: 'experiment_123',
variant_id: 'variant_a'
});
// Отслеживание конверсии в эксперименте
gtag('event', 'experiment_conversion', {
experiment_id: 'experiment_123',
variant_id: 'variant_a'
});Performance analysis
Tracking Core Web Vitals:
// Отслеживание LCP
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
gtag('event', 'web_vitals', {
event_category: 'Web Vitals',
event_label: 'LCP',
value: Math.round(entry.startTime),
non_interaction: true
});
}
}).observe({entryTypes: ['largest-contentful-paint']});
// Отслеживание FID
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
gtag('event', 'web_vitals', {
event_category: 'Web Vitals',
event_label: 'FID',
value: Math.round(entry.processingStart - entry.startTime),
non_interaction: true
});
}
}).observe({entryTypes: ['first-input']});
// Отслеживание CLS
new PerformanceObserver((entryList) => {
let clsValue = 0;
for (const entry of entryList.getEntries()) {
clsValue += entry.value;
}
gtag('event', 'web_vitals', {
event_category: 'Web Vitals',
event_label: 'CLS',
value: Math.round(clsValue * 1000) / 1000,
non_interaction: true
});
}).observe({entryTypes: ['layout-shift']});Security and privacy
GDPR and CCPA
Configuring consent:
// Отслеживание согласия пользователя
gtag('consent', 'default', {
'analytics_storage': 'denied',
'ad_storage': 'denied'
});
// Обновление согласия
function updateConsent(analytics, ads) {
gtag('consent', 'update', {
'analytics_storage': analytics ? 'granted' : 'denied',
'ad_storage': ads ? 'granted' : 'denied'
});
}Blocking tracking:
// Проверка Do Not Track
if (navigator.doNotTrack === '1') {
// Отключить отслеживание
return;
}
// Проверка согласия
if (!hasUserConsent()) {
// Отключить отслеживание
return;
}Data filtering
Excluding internal traffic:
- Settings → Filters
- Create a new filter
- Exclude IP addresses
Spam filtering:
// Фильтрация ботов
if (navigator.userAgent.includes('bot')) {
return;
}
// Фильтрация по времени на странице
let minTimeOnPage = 5000; // 5 секундBest practices
1. Planning
- Identify key metrics
- Create a tracking plan
- Set up goals and conversions
- Define audience segments
2. Implementation
- Use the right events
- Configure Enhanced Ecommerce
- Track custom events
- Set up filters
3. Analysis
- Review data regularly
- Create custom reports
- Analyze conversion funnels
- Track trends
4. Optimization
- Run A/B tests
- Optimize based on data
- Track Core Web Vitals
- Improve the user experience
Conclusion
Google Analytics 4 is a powerful tool for analyzing websites. Properly configuring and using GA4 lets you collect valuable data about user behavior and website performance.
Key points to remember:
- Set up GA4 correctly from the start
- Track important events to understand user behavior
- Set up goals and conversions to measure performance
- Use custom reports for in-depth analysis
- Meet privacy requirements (GDPR, CCPA)
- Analyze data regularly and optimize your website
By following these recommendations, you can get the most out of Google Analytics 4 and use data to improve your website.