일상 블로그 배경
일상 블로그

구글 애널리틱스(GA4) 위젯 설치하기: 실시간 방문자와 유입 경로 확인하기

티스토리 관리자 전용 실시간 구글 애널리틱스 위젯 만들기: GA4 API와 구글 앱스 스크립트 활용법

매번 구글 애널리틱스 사이트에 접속해 통계를 확인하는 것이 번거롭지 않으셨나요? GA4 API를 이용해 티스토리 블로그에 관리자 전용 실시간 방문자 위젯을 설치하면, 블로그 안에서 바로 핵심 데이터를 확인할 수 있습니다.


티스토리 관리자 화면에서 제공하는 방문자 수보다 더 정교한 분석을 원한다면, 구글 애널리틱스(GA4) 데이터를 활용한 방문자 분석이 필수입니다. 티스토리 자체 통계는 서버에 요청된 단순한 호출 수(Page View)를 기준으로 집계되지만, 구글 애널리틱스는 실제 사용자의 행동 데이터를 기반으로 분석하기 때문에 블로그 운영과 전략 수립에 훨씬 큰 도움이 됩니다.

오늘은 구글의 강력한 Analytics API를 활용해 내 블로그의 실제 방문 흐름과 내 블로그의 체력을 정확히 확인하고, 관리자에게만 노출되는 보안 구글 애널리틱스 위젯을 설치하는 실전 방법을 자세히 알아보겠습니다.

어떤 콘텐츠가 실제로 읽히고 있는지, 그리고 독자가 어디에서 반응하고 머무는지가 그대로 담겨 있습니다. 콘텐츠가 검색 결과를 넘어 누군가의 문제를 해결하고 공감을 얻기 시작할 때, 그 흐름은 방문자 데이터로 가장 먼저 드러납니다.

데이터를 보지 않고 글을 쓰는 것은 감에 의존해 방향을 정하는 것과 다르지 않습니다. 반면 정확한 방문자 분석은 불필요한 시도를 줄이고, 성과가 나는 콘텐츠에 집중할 수 있도록 기준을 만들어 줍니다. 특히 수익을 목적으로 블로그를 운영한다면, 방문자 데이터는 광고 성과와 블로그의 시장 가치를 판단하는 가장 현실적인 지표가 됩니다.

1. 구글 애널리틱스 위젯 연동을 위한 내 블로그 사이트 등록

1단계: 계정 및 속성 만들기

구글 애널리틱스 위젯 설치 방법

먼저 구글 애널리틱스 공식 사이트에 접속하여 내 블로그를 위한 공간을 만들어야 합니다.

  1. 구글 애널리틱스 접속 후 로그인합니다.
  2. [측정 시작] 버튼을 누릅니다.
  3. 계정 설정: 계정 이름에 블로그 이름이나 본인 닉네임을 적습니다.
  4. 속성 설정: 속성 이름을 적고 보고 시간대를 대한민국으로 설정합니다.
구글 애널리틱스 계정 등록 화면
블로그 방문자 통계 애널리스틱 등록

2단계: 데이터 스트림 설정 및 위젯 소스 확보

이제 구글 애널리틱스가 어디서 데이터를 가져올지 정해야 합니다. 플랫폼에서 [웹]을 선택하고 본인의 티스토리 주소를 입력하세요.

구글 애널리틱스 플랫폼 선택화면

트래픽 분석 애널리스틱 플래폼 설정 화면

3단계: 티스토리에 '측정 ID' 연결하여 구글 애널리틱스 위젯 활성화하기

스트림을 생성하면 G-로 시작하는 측정 ID가 발급됩니다. 이 ID를 통해 데이터 수집을 시작합니다.

구글 애널리스틱 측정 아이디 확인 방법
구글 애널리스틱 계정 아이디 확인 화면

플러그인 대신 수동 스크립트 사용을 권장합니다. 아래 코드를 HTML의 head 태그 안에 넣어주세요.

<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
(function() {
const isMobile = /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);
const deviceCategory = isMobile ? 'mobile' : 'desktop';
gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': true,
'device_type': deviceCategory
});
})();
</script>

2. 구글 애널리틱스 위젯 등록 확인 방법

설정 후 1분 뒤 본인 블로그에 접속하여 구글 애널리틱스 [보고서] > [실시간] 메뉴에서 방문자가 체크되는지 확인하세요. 위젯 호출에는 9자리 '속성 ID'가 사용됩니다.


3. 준비 단계: 구글 애널리틱스 API 및 속성 ID 설정

구글 클라우드 콘솔에서 프로젝트를 생성하고 "Google Analytics Data API"를 사용 설정해야 위젯이 정상 작동합니다.


4. 중간 단계: 구글 앱스 스크립트(GAS) 서버 구축

블로그 속도 저하를 막기 위해 구글 앱스 스크립트로 데이터 연산을 처리합니다.

function doGet(e) {
  // 🔐 관리자 접근용 비밀번호 (본인이 정한 값으로 직접 입력)
  const SECRET_PASSWORD = '여기에_관리자_비밀번호_입력';
  const userToken = e.parameter.token;

  if (userToken !== SECRET_PASSWORD) {
    return ContentService.createTextOutput(
      JSON.stringify({ error: "비정상적인 접근입니다." })
    ).setMimeType(ContentService.MimeType.JSON);
  }

  // 📊 GA4 속성 ID (GA4 관리자 > 속성 설정에서 확인 후 입력)
  const propertyId = '여기에_GA4_PROPERTY_ID_입력';

  try {
    // 1️⃣ 실시간 방문자 수
    const realtimeRequest = {
      metrics: [{ name: "activeUsers" }]
    };

    const realtimeReport = AnalyticsData.Properties.runRealtimeReport(
      realtimeRequest,
      `properties/${propertyId}`
    );

    // 2️⃣ 오늘 누적 페이지뷰
    const totalRequest = {
      dateRanges: [{ startDate: "today", endDate: "today" }],
      metrics: [{ name: "screenPageViews" }]
    };

    const totalReport = AnalyticsData.Properties.runReport(
      totalRequest,
      `properties/${propertyId}`
    );

    let result = {
      activeUsers: 0, // 실시간 방문자
      pageViews: 0    // 오늘 누적 조회수
    };

    if (realtimeReport.rows?.length) {
      result.activeUsers = Number(
        realtimeReport.rows[0].metricValues[0].value
      );
    }

    if (totalReport.rows?.length) {
      result.pageViews = Number(
        totalReport.rows[0].metricValues[0].value
      );
    }

    return ContentService.createTextOutput(JSON.stringify(result))
      .setMimeType(ContentService.MimeType.JSON);

  } catch (err) {
    return ContentService.createTextOutput(
      JSON.stringify({ error: err.message })
    ).setMimeType(ContentService.MimeType.JSON);
  }
}

}

5. 마지막 단계: 티스토리 사이드바 구글 애널리틱스 위젯 적용

관리자(owner)에게만 보이고 2분마다 자동 갱신되는 실시간 위젯 최종 코드입니다.

<div id="ga-admin-wrapper" style="display:none; max-width:280px; min-width:250px; margin: 10px 0;">
<div id="ga-stats-widget" style="background:#111; color:#fff; padding:15px; border-radius:15px; font-family:sans-serif; border:1px solid #333; box-shadow:0 8px 20px rgba(0,0,0,0.4);">
<div id="ga-title" style="font-size:11px; color:#fff; font-weight:bold; letter-spacing:1px; margin-bottom:15px; text-align:center;">관리자 전용 구글 애널리틱스 위젯</div>
<div id="ga-auth-area" style="text-align:center; display:none;">
<input type="password" id="ga-pwd-input" placeholder="Password" style="background:#222; border:1px solid #444; color:#fff; padding:8px; border-radius:5px; width:80%; font-size:12px; outline:none; margin-bottom:10px;">
<button onclick="handleManualAuth()" style="background:#00e5ff; border:none; color:#000; padding:8px; border-radius:5px; cursor:pointer; font-weight:bold; font-size:11px; width:88%;">인증 및 접속</button>
</div>
<div id="ga-data-area" style="display:none;">
<div style="display:flex; justify-content:space-around; align-items:center;">
<div style="text-align:center;">
<div style="font-size:10px; color:#fff; margin-bottom:5px; font-weight:bold;">USERS</div>
<div id="ga-users" style="font-size:26px; font-weight:bold; color:#00ff00;">-</div>
</div>
<div style="width:1px; height:30px; background:#333;"></div>
<div style="text-align:center;">
<div style="font-size:10px; color:#fff; margin-bottom:5px; font-weight:bold;">VIEWS</div>
<div id="ga-views" style="font-size:26px; font-weight:bold; color:#ffcc00;">-</div>
</div>
</div>
</div>
<div id="ga-status" style="font-size:9px; color:#fff; margin-top:15px; text-align:center; opacity:0.6;">접속 확인 중...</div>
</div>
</div>
<script>
const BASE_URL = 'https://script.google.com/macros/s/SAMPLE_ID/exec';
async function fetchGA4Data(pwd) {
const res = await fetch(BASE_URL + '?token=' + encodeURIComponent(pwd));
const data = await res.json();
if (data.error) throw new Error(data.error);
return data;
}
function updateGA4UI(data) {
document.getElementById('ga-auth-area').style.display = 'none';
document.getElementById('ga-data-area').style.display = 'block';
document.getElementById('ga-users').innerText = Number(data.activeUsers).toLocaleString();
document.getElementById('ga-views').innerText = Number(data.pageViews).toLocaleString();
document.getElementById('ga-status').innerText = "Last Update: " + new Date().toLocaleTimeString();
}
async function handleManualAuth() {
const pwd = document.getElementById('ga-pwd-input').value;
if (!pwd) return alert("비밀번호를 입력하세요.");
executeAuth(pwd);
}
async function executeAuth(pwd) {
const statusEl = document.getElementById('ga-status');
statusEl.innerText = "서버 승인 중...";
try {
const data = await fetchGA4Data(pwd);
localStorage.setItem('ga4_token_val', pwd);
updateGA4UI(data);
setInterval(async () => {
try { const d = await fetchGA4Data(pwd); updateGA4UI(d); } catch (e) {}
}, 120000);
} catch (e) {
localStorage.removeItem('ga4_token_val');
document.getElementById('ga-auth-area').style.display = 'block';
document.getElementById('ga-data-area').style.display = 'none';
statusEl.innerText = "인증 실패: 다시 시도하세요.";
}
}
(function() {
if (window.T && window.T.config && window.T.config.ROLE === 'owner') {
document.getElementById('ga-admin-wrapper').style.display = 'block';
const savedPwd = localStorage.getItem('ga4_token_val');
if (savedPwd) executeAuth(savedPwd);
else {
document.getElementById('ga-auth-area').style.display = 'block';
document.getElementById('ga-status').innerText = "인증이 필요합니다.";
}
}
})();
</script>

실시간 방문자 데이터를 관리자만 볼 수 있도록 구글 애널리틱스 위젯을 설치해 보세요.