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).
Configure Astro
Make sure you install the @astrojs/vercel
package as described in the docs and configure it to enable analytics.
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:
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:
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:
With this fix applied, everything started working as expected 🎉. Now stats can go to the moon 🚀.