Skip to content


Switch branches/tags

Latest commit


Git stats


Failed to load latest commit information.

Svelte Google Analytics

js-standard-style Svelte v3

Supports Google Analytics v4!

Install the package

pnpm i --save-dev @beyonk/svelte-google-analytics


In App.svelte

import { GoogleAnalytics } from '@beyonk/svelte-google-analytics'

<GoogleAnalytics properties={[ 'google property id A', ...'google property id X' ]} />

Component accepts two additional properties: enabled and configurations.

The configurations property (optional)

configurations props which accepts an object type with configurations for the properties. The key in this object is the id of the property. Example on disabling automatic pageviews for the id-1 property:

    properties={[ 'id-1' ]}
    configurations={{ 'id-1': { 'send_page_view': false } }} />

The enabled property (optional)

The enabled prop set to true by default. Logic can be added here to disable/enable analytics.

If you disable tracking by default, for instance, due to GDPR, then you can enable it later by calling init() on your component:

    properties={[ 'id-1' ]}
    enabled={false} />

  function enableAnalytics () {

Page Tracking

With Google Analytics v4, most basic events are automatic. See the docs

(see Google Analytics offical docs - Pageviews) for more info


Event Tracking

All events specified in the documentation are implemeneted (generated automatically from scraping the docs pages and building the project!)

  import { ga } from '@beyonk/svelte-google-analytics'

  function handleClick () {'SvelteBucks', 50)

  <button on:click={handleClick}>Get 50 SvelteBucks</button>

Custom Events

Custom events can be tracked with addEvent:

  import { ga } from '@beyonk/svelte-google-analytics'

  function handleClick () {
    ga.addEvent('event_name', {
      foo: 'bar',
      baz: 'qux'

Multiple Properties

To send an event to a different property, specify the property id as the last parameter to the event: send_to.'SvelteBucks', 50, 'Property Id B')

Set User Properties

To split user to different segment, such as language preference or geographic location, set the Properties with setUserProperties and setup custom dimension on Google Analytics dashboard. For more information see Google Analytics Documentation.

  favorite_composer: 'Mahler',
  favorite_instrument: 'double bass',
  season_ticketholder: 'true'

Set User Id

To identify user inside GA and link their sessions together, set the Properties with setUserId.


Set config

To add a Google Analytics ID after initialization call the setConfig and pass optional configuration options.

ga.setConfig('ga_id', opts)