DEV Community

Luke Hagar
Luke Hagar

Posted on

Using Vercel Analytics with SvelteKit

Vercel's guide on utilizing Analytics on SvelteKit have improved, but regardless I wanted to provide an example of a successful implementation on my profile site.

First install @vercel/analytics

npm install -D @vercel/analytics
Enter fullscreen mode Exit fullscreen mode

Next import the analytics package in your root +layout.svelte file.

    // Import the Analytics package, and the SvelteKit dev variable.
    import { dev } from '$app/environment';
    import { inject } from '@vercel/analytics';
Enter fullscreen mode Exit fullscreen mode

Finally run the inject function with the mode being determined by the Dev variable setting

    // Inject the Analytics functionality
    inject({ mode: dev ? 'development' : 'production' });
Enter fullscreen mode Exit fullscreen mode

Here is my final +layout.svelte file for reference

<script lang="ts">
    import Header from '$lib/Header.svelte';
    import '$lib/theme-luke.css';
    import { AppShell } from '@skeletonlabs/skeleton';
    import '@skeletonlabs/skeleton/styles/all.css';
    import '../app.postcss';

    // Import the Analytics package, and the SvelteKit dev variable.
    import { dev } from '$app/environment';
    import { inject } from '@vercel/analytics';

    // Inject the Analytics functionality
    inject({ mode: dev ? 'development' : 'production' });
</script>

<!-- App Shell -->
<AppShell slotSidebarLeft="bg-surface-500/5 w-56 p-4">
    <svelte:fragment slot="header">
        <!-- App Bar -->
        <Header />
    </svelte:fragment>
    <!-- Page Route Content -->
    <slot />
</AppShell>
Enter fullscreen mode Exit fullscreen mode

After everything is implemented as above, you just need to ensure that Vercel analytics is enabled correctly on the Vercel project and your data will begin populating the next time somebody accesses the webpage.

Be good people, and happy development!

Top comments (0)