DEV Community

Luke Hagar
Luke Hagar

Posted on

1

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
paperrocketeer profile image
Abdiel Lopez

Does it need to go inside of the onMount() for it to work with SSR?

Collapse
 
lukehagar profile image
Luke Hagar

onMount() or adding a browser check should do it

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more