@repo/analytics
Svelte wrapper around (analytics)[https://github.com/DavidWells/analytics]
Page view
// +layout.svelte
<script lang='ts'>
import { trackPageView } from '@repo/analytics'
import { analytics } from '$lib/library/analytics'
onMount(async () => {
trackPageView(analytics)
})
</script>
Cookiewall
// +layout.svelte
<script lang='ts'>
import { CookieWall } from '@repo/analytics'
import { Analytics } from 'analytics'
const analytics = Analytics({
app: 'boiler',
plugins: [
googleAnalytics({
measurementIds: ['G-XXXXXXXX'],
enabled: false // IMPORTANT: This should always be false and be controlled by the cookiewall
}),
],
})
</script>
<CookieWall {analytics} plugins={['google-analytics']} />
Directives
This package comes with baked in directives. Not all are necessary for every plugin.
createTrackClickDirective
// lib/analytics/directives.ts
import { analytics } from './analytics'
import { createTrackClickDirective } from '@repo/analytics'
const trackClick = createTrackClickDirective(analytics, 'clicked')
<script lang='ts'>
import { trackClick } from '$lib/analytics/directives.ts'
</script>
<button use:trackClick={{ type: 'login' }}>Login</button>
createOutboundLinkDirective
// lib/analytics/directives.ts
import { analytics } from './analytics'
import { createTrackOutboundLinkDirective } from '@repo/analytics'
const trackOutbound = createTrackOutboundLinkDirective(analytics, 'outbound')
<script lang='ts'>
import { trackOutbound } from '$lib/analytics/directives.ts'
</script>
<a href="https://google.com" use:trackOutbound>Test</button>
createTrackFormSubmitDirective
// lib/analytics/directives.ts
import { analytics } from './analytics'
import { createTrackOutboundLinkDirective } from '@repo/analytics'
const trackOutbound = createTrackFormSubmitDirective(analytics, 'submit')
<script lang='ts'>
import { trackFormSubmit } from '$lib/analytics/directives.ts'
</script>
<form use:trackFormSubmit>
<button type="Submit">Submit</button>
</form>
Plugins
This library also adds plugins upon the analytics plugin directory.
Posthog
pnpm add posthog-js
export const analytics = Analytics({
app: 'boiler',
plugins: [
posthogPlugin({
apiKey: '...',
initSettings: {
api_host: 'https://eu.i.posthog.com',
person_profiles: 'identified_only',
},
}),
],
})