← 목록으로

Google Analytics란?

Google Analytics 완벽 가이드: 웹사이트 데이터 분석의 시작

서론

Google Analytics는 웹사이트의 방문자 행동을 분석하고 이해하는 데 필수적인 도구입니다. 사용자가 어디서 왔는지, 어떤 페이지를 보는지, 얼마나 오래 머무는지 등 다양한 데이터를 수집하여 비즈니스 의사결정에 활용할 수 있습니다. 이 글에서는 Google Analytics 4(GA4)를 중심으로 설정부터 고급 활용까지 다루겠습니다.

1. Google Analytics란?

1.1 Google Analytics의 역할

Google Analytics는 웹사이트 트래픽과 사용자 행동을 추적하고 분석하는 무료 웹 분석 도구입니다.

주요 기능:

  • 방문자 수 추적
  • 사용자 행동 분석
  • 트래픽 소스 파악
  • 전환 추적
  • 실시간 모니터링

1.2 GA4 vs Universal Analytics

GA4의 주요 변화:

  • 이벤트 기반 추적 모델
  • 향상된 개인정보 보호
  • 머신러닝 기반 인사이트
  • 크로스 플랫폼 추적
  • 더 나은 데이터 분석 도구

2. Google Analytics 설정

2.1 계정 생성 및 속성 설정

  1. Google Analytics 웹사이트 접속
  2. 계정 생성
  3. 속성(Property) 생성
  4. 데이터 스트림 설정
  5. 측정 ID 획득 (G-XXXXXXXXXX)

2.2 Next.js에 Google Analytics 추가

// app/layout.js
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="ko">
      <body>
        <Script
          src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
          strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
          `}
        </Script>
        {children}
      </body>
    </html>
  );
}

2.3 환경 변수 설정

# .env.local
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX

3. 기본 페이지뷰 추적

3.1 자동 페이지뷰 추적

// app/layout.js
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

export function Analytics() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (typeof window !== 'undefined' && window.gtag) {
      const url = pathname + (searchParams?.toString() ? `?${searchParams.toString()}` : '');
      window.gtag('config', process.env.NEXT_PUBLIC_GA_ID, {
        page_path: url,
      });
    }
  }, [pathname, searchParams]);

  return null;
}

3.2 커스텀 페이지뷰 이벤트

'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

export default function PageViewTracker() {
  const pathname = usePathname();

  useEffect(() => {
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'page_view', {
        page_path: pathname,
        page_title: document.title,
      });
    }
  }, [pathname]);

  return null;
}

4. 커스텀 이벤트 추적

4.1 버튼 클릭 추적

'use client';

export default function ButtonWithTracking() {
  const handleClick = () => {
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'button_click', {
        button_name: '다운로드',
        button_location: 'hero_section',
      });
    }
    
    // 실제 버튼 동작
    downloadFile();
  };

  return (
    <button onClick={handleClick}>
      다운로드
    </button>
  );
}

4.2 폼 제출 추적

'use client';

export default function ContactForm() {
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 폼 데이터 처리
    const formData = new FormData(e.target);
    
    // Google Analytics 이벤트 추적
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'form_submit', {
        form_name: 'contact_form',
        form_location: 'contact_page',
      });
    }
    
    // API 호출 등
    await submitForm(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" required />
      <input name="email" type="email" required />
      <button type="submit">제출</button>
    </form>
  );
}

4.3 파일 다운로드 추적

'use client';

export default function DownloadLink({ fileUrl, fileName }) {
  const handleDownload = () => {
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'file_download', {
        file_name: fileName,
        file_extension: fileName.split('.').pop(),
        link_url: fileUrl,
      });
    }
    
    // 다운로드 실행
    window.open(fileUrl, '_blank');
  };

  return (
    <a onClick={handleDownload} href={fileUrl}>
      {fileName} 다운로드
    </a>
  );
}

5. 전환 추적

5.1 구매 전환 추적

'use client';

export default function PurchaseComplete({ order }) {
  useEffect(() => {
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'purchase', {
        transaction_id: order.id,
        value: order.total,
        currency: 'KRW',
        items: order.items.map(item => ({
          item_id: item.id,
          item_name: item.name,
          price: item.price,
          quantity: item.quantity,
        })),
      });
    }
  }, [order]);

  return <div>구매 완료</div>;
}

5.2 회원가입 전환 추적

const handleSignUp = async (userData) => {
  try {
    const user = await createUser(userData);
    
    // 전환 이벤트 추적
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'sign_up', {
        method: 'email',
      });
    }
    
    return user;
  } catch (error) {
    console.error('회원가입 실패:', error);
  }
};

6. 사용자 속성 추적

6.1 사용자 ID 설정

'use client';

import { useEffect } from 'react';

export default function UserTracker({ userId }) {
  useEffect(() => {
    if (typeof window !== 'undefined' && window.gtag && userId) {
      window.gtag('set', { user_id: userId });
    }
  }, [userId]);

  return null;
}

6.2 커스텀 사용자 속성

const setUserProperties = (properties) => {
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('set', 'user_properties', {
      membership_type: properties.membershipType,
      subscription_status: properties.subscriptionStatus,
    });
  }
};

7. 실시간 모니터링

7.1 실시간 이벤트 추적

'use client';

export default function RealtimeTracker() {
  const trackEvent = (eventName, parameters) => {
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', eventName, {
        ...parameters,
        timestamp: new Date().toISOString(),
      });
    }
  };

  return (
    <div>
      <button onClick={() => trackEvent('video_play', { video_title: 'Tutorial' })}>
        비디오 재생
      </button>
    </div>
  );
}

8. 고급 추적 기능

8.1 스크롤 깊이 추적

'use client';

import { useEffect } from 'react';

export default function ScrollTracker() {
  useEffect(() => {
    const trackScrollDepth = () => {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const docHeight = document.documentElement.scrollHeight - window.innerHeight;
      const scrollPercent = Math.round((scrollTop / docHeight) * 100);

      if (scrollPercent === 25 || scrollPercent === 50 || scrollPercent === 75 || scrollPercent === 100) {
        if (typeof window !== 'undefined' && window.gtag) {
          window.gtag('event', 'scroll', {
            scroll_depth: scrollPercent,
          });
        }
      }
    };

    window.addEventListener('scroll', trackScrollDepth);
    return () => window.removeEventListener('scroll', trackScrollDepth);
  }, []);

  return null;
}

8.2 외부 링크 클릭 추적

'use client';

import { useEffect } from 'react';

export default function ExternalLinkTracker() {
  useEffect(() => {
    const handleLinkClick = (e) => {
      const link = e.target.closest('a');
      if (!link) return;

      const href = link.getAttribute('href');
      if (href && (href.startsWith('http') && !href.includes(window.location.hostname))) {
        if (typeof window !== 'undefined' && window.gtag) {
          window.gtag('event', 'click', {
            event_category: 'outbound',
            event_label: href,
            transport_type: 'beacon',
          });
        }
      }
    };

    document.addEventListener('click', handleLinkClick);
    return () => document.removeEventListener('click', handleLinkClick);
  }, []);

  return null;
}

8.3 비디오 재생 추적

'use client';

import { useRef, useEffect } from 'react';

export default function VideoTracker({ videoUrl }) {
  const videoRef = useRef(null);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const trackVideoEvent = (eventName, value) => {
      if (typeof window !== 'undefined' && window.gtag) {
        window.gtag('event', eventName, {
          video_title: videoUrl,
          video_current_time: video.currentTime,
          video_duration: video.duration,
          video_percent: value,
        });
      }
    };

    video.addEventListener('play', () => trackVideoEvent('video_play'));
    video.addEventListener('pause', () => trackVideoEvent('video_pause'));
    video.addEventListener('ended', () => trackVideoEvent('video_complete'));

    // 재생 진행률 추적
    video.addEventListener('timeupdate', () => {
      const percent = Math.round((video.currentTime / video.duration) * 100);
      if (percent === 25 || percent === 50 || percent === 75) {
        trackVideoEvent('video_progress', percent);
      }
    });

    return () => {
      video.removeEventListener('play', trackVideoEvent);
      video.removeEventListener('pause', trackVideoEvent);
      video.removeEventListener('ended', trackVideoEvent);
    };
  }, [videoUrl]);

  return <video ref={videoRef} src={videoUrl} controls />;
}

9. 주요 지표 이해하기

9.1 사용자 지표

  • 사용자 수: 웹사이트를 방문한 고유 사용자 수
  • 신규 사용자: 처음 방문한 사용자
  • 재방문 사용자: 이전에 방문한 적이 있는 사용자

9.2 행동 지표

  • 세션 수: 사용자 세션의 총 수
  • 페이지뷰: 조회된 페이지 수
  • 평균 세션 시간: 사용자가 사이트에 머문 평균 시간
  • 이탈률: 한 페이지만 보고 떠난 세션 비율

9.3 전환 지표

  • 전환 수: 목표로 설정한 행동 완료 횟수
  • 전환율: 세션 대비 전환 비율
  • 전환 가치: 전환으로 인한 수익

10. 목표 설정

10.1 GA4에서 목표 설정

  1. Google Analytics 관리 페이지 접속
  2. 이벤트 섹션으로 이동
  3. 마크를 이벤트로 표시
  4. 전환 이벤트로 설정

10.2 커스텀 목표 예시

// 목표 이벤트 예시
const goals = {
  newsletter_signup: {
    event_name: 'newsletter_signup',
    conversion_value: 1,
  },
  product_view: {
    event_name: 'view_item',
    conversion_value: 0.5,
  },
  add_to_cart: {
    event_name: 'add_to_cart',
    conversion_value: 2,
  },
  purchase: {
    event_name: 'purchase',
    conversion_value: 10,
  },
};

11. 데이터 분석과 리포트

11.1 주요 리포트 활용

실시간 리포트:

  • 현재 방문자 수
  • 실시간 이벤트
  • 트래픽 소스

획득 리포트:

  • 사용자 획득 경로
  • 채널별 성과
  • 캠페인 효과

참여도 리포트:

  • 페이지 및 화면
  • 이벤트 분석
  • 전환 경로

수익화 리포트:

  • 전환 이벤트
  • 수익 추적
  • 구매 행동 분석

11.2 커스텀 리포트 생성

// 커스텀 대시보드 데이터 수집
const customReport = {
  page_views: getPageViews(),
  unique_visitors: getUniqueVisitors(),
  average_session_duration: getAverageSessionDuration(),
  conversion_rate: getConversionRate(),
  top_pages: getTopPages(),
  traffic_sources: getTrafficSources(),
};

12. 개인정보 보호 고려사항

12.1 쿠키 동의 관리

'use client';

import { useState, useEffect } from 'react';

export default function CookieConsent() {
  const [consent, setConsent] = useState(null);

  useEffect(() => {
    const savedConsent = localStorage.getItem('ga_consent');
    setConsent(savedConsent);
  }, []);

  const handleAccept = () => {
    localStorage.setItem('ga_consent', 'granted');
    setConsent('granted');
    
    // Google Analytics 활성화
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('consent', 'update', {
        analytics_storage: 'granted',
      });
    }
  };

  const handleReject = () => {
    localStorage.setItem('ga_consent', 'denied');
    setConsent('denied');
    
    // Google Analytics 비활성화
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('consent', 'update', {
        analytics_storage: 'denied',
      });
    }
  };

  if (consent !== null) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-gray-800 text-white p-4">
      <p>쿠키 사용에 동의하시겠습니까?</p>
      <button onClick={handleAccept}>동의</button>
      <button onClick={handleReject}>거부</button>
    </div>
  );
}

12.2 IP 익명화

// app/layout.js
<Script id="google-analytics" strategy="afterInteractive">
  {`
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
      anonymize_ip: true,
    });
  `}
</Script>

13. 성능 최적화

13.1 지연 로딩

'use client';

import { useEffect, useState } from 'react';

export default function LazyAnalytics() {
  const [shouldLoad, setShouldLoad] = useState(false);

  useEffect(() => {
    // 사용자 상호작용 후 로드
    const handleInteraction = () => {
      setShouldLoad(true);
      window.removeEventListener('scroll', handleInteraction);
      window.removeEventListener('click', handleInteraction);
    };

    window.addEventListener('scroll', handleInteraction, { once: true });
    window.addEventListener('click', handleInteraction, { once: true });

    return () => {
      window.removeEventListener('scroll', handleInteraction);
      window.removeEventListener('click', handleInteraction);
    };
  }, []);

  useEffect(() => {
    if (!shouldLoad) return;

    const script = document.createElement('script');
    script.src = `https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`;
    script.async = true;
    document.head.appendChild(script);

    window.dataLayer = window.dataLayer || [];
    function gtag(){window.dataLayer.push(arguments);}
    window.gtag = gtag;
    gtag('js', new Date());
    gtag('config', process.env.NEXT_PUBLIC_GA_ID);
  }, [shouldLoad]);

  return null;
}

14. 결론

Google Analytics는 웹사이트의 성과를 측정하고 개선점을 찾는 데 필수적인 도구입니다. 기본적인 페이지뷰 추적부터 커스텀 이벤트, 전환 추적까지 다양한 기능을 활용하여 사용자 행동을 이해하고 비즈니스 목표를 달성할 수 있습니다.

주요 포인트:

  • 기본 설정: 측정 ID 설정과 페이지뷰 추적
  • 커스텀 이벤트: 버튼 클릭, 폼 제출 등 사용자 행동 추적
  • 전환 추적: 구매, 회원가입 등 목표 달성 측정
  • 고급 기능: 스크롤, 외부 링크, 비디오 재생 추적
  • 개인정보 보호: 쿠키 동의 및 IP 익명화
  • 성능 최적화: 지연 로딩으로 초기 로딩 속도 개선

정확한 데이터 수집과 분석을 통해 사용자 경험을 개선하고 비즈니스 성장을 이끌 수 있습니다.