POSTS / Use Google Analytics in Blog Page

Published: 2024-01-31
Updated:   2024-02-02

First, register an account in Home: Google Analytics.

After you fill all the forms, create one website app on that platform.


Click that button and paste the code immediately after the head element then everything will be OK.

Found one alternative for Svelte:

Create src/lib/Analytics.svelte:

<script lang="ts">
  import { page } from '$app/stores'

  $: {
    if (typeof gtag !== 'undefined') {
      gtag('config', 'MEASUREMENT_ID', {
        page_title: document.title,
        page_path: $page.url.pathname,

    window.dataLayer = window.dataLayer || []

    function gtag() {

    gtag('js', new Date())
    gtag('config', 'MEASUREMENT_ID')

Optional step is to install the type definitions for gtag.js with npm i -D @types/gtag.js.

This is how you can measure information such as the page title and page path using the SvelteKit store.

Because it’s using a store value whenever the page gets updated inside the $: { ... } reactive block we can submit the new page view if gtag exists on window meaning it’s inside the browser context.

Include the Analytics component inside your main layout __layout.svelte making it available on every page.

<script lang="ts">
  import Analytics from '$lib/analytics.svelte'

<Analytics />

<slot />

That’s it! 🎉

[!WARNING] If you’re using an ad blocker you’re going to see the net::ERR_BLOCKED_BY_CLIENT error in your console as it gets blocked by those extensions — so if you have a tech savvy audience you might want to look into other options.

Referred from Google Analytics With SvelteKit.