Vercel Analytics with Astro: To The Moon 🚀

  • #analytics
  • #astro
  • #vercel
  • #webvitals

Integrating Vercel Analytics with Astro is a breeze, or so they say. Unfortunately, it’s not as easy as it seems. In this blog post, I’ll walk you through the actual process and fill in the gaps left by the documentation.

By following the steps outlined here, I was able to successfully implement Web Vitals and Audience Analytics on my personal website - the very site you’re visiting now, which is a static site generated with Astro (no SSR enabled).

Vector art of a website user statistics chart in a space environment with a rocket going to the moon.
With Vercel Analytics to the moon 🚀, but with some required workarounds.

Configure Astro

Make sure you install the @astrojs/vercel package as described in the docs and configure it to enable analytics.

/// astro.config.mjs
import { defineConfig } from 'astro/config'
import vercel from '@astrojs/vercel/static'
export default defineConfig({
output: 'static',
adapter: vercel({
analytics: true,
}),
})

Make sure you import vercel from the correct adapter export that you are building for (serverless, edge, static). In my case it is @astrojs/vercel/static.

Configure Vercel

In the Vercel dashboard, enable the Analytics feature for your project. This is where I ran into the first problem. After enabling the Web Vitals feature (which I was going for at the time), I was greeted with the following error after deploying my site:

404 [Not Found] /_vercel/insights/script.js

It turns out that you also need to enable the Audiences feature to make the analytics per se work in Astro. It will then deploy the missing script to your site. There is no mention of this in the docs, so I had to figure it out myself with a little help from GitHub.

Web Vitals are not coming in

The next problem was that the Web Vitals data was not coming in to the Vercel dashboard. The browser console indicated that an environment variable was missing:

[Analytics] VERCEL_ANALYTICS_ID not found

Turns out there is a bug in the @astrojs/vercel package that tries to load PUBLIC_VERCEL_ANALYTICS_ID, but Vercel defines your analytics ID as VERCEL_ANALYTICS_ID.

But thanks to Astro’s Discord I found a workaround for this problem as well:

/// astro.config.mjs
vite: {
define: {
'import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID':
JSON.stringify(
process.env.VERCEL_ANALYTICS_ID
),
},
},

With this fix applied, everything started working as expected 🎉. Now stats can go to the moon 🚀.