← All posts

Vercel Analytics on a static Astro site

· Astro, Vercel, Performance

I wanted Vercel Web Analytics on this site. Vercel opened a pull request to set it up for me, which was nice. Then I read what it changed.

What the pull request did

It added two packages, @astrojs/vercel and @vercel/analytics, and changed astro.config.mjs like this:

output: 'server',
adapter: vercel({
  webAnalytics: { enabled: true }
}),

The build passed, so it looked fine. The problem is output: 'server'. This site is static. Astro builds every page once, and Vercel serves the HTML files. With server, every page gets rendered again on each visit.

That hits one page hard. /mobifreaks asks the GitHub API for the list of my old template repos. In a static build that happens once, at build time. With server, it would happen on every visit to the page. That is slower, and GitHub limits how often you can call its API.

Two script tags instead

Vercel also documents a plain script snippet. On a Vercel deployment, the script is served from your own domain at /_vercel/insights/script.js, so no package is needed. I removed both packages and the adapter, and added this to my analytics component:

---
const vercel = import.meta.env.PROD && process.env.VERCEL === '1';
---

{
  vercel && (
    <Fragment>
      <script is:inline>
        window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };
      </script>
      <script is:inline defer src="/_vercel/insights/script.js"></script>
    </Fragment>
  )
}
  • vercel is true only in a production build on Vercel. Locally, or anywhere else, the /_vercel path doesn’t exist, so the tags are left out.
  • The small inline script queues any events sent before the main script loads.
  • defer means the script never holds up the page.

I added Speed Insights the same way, with window.si and /_vercel/speed-insights/script.js.

What I got

  • The site is still fully static. output: 'server' and the adapter are gone.
  • Two fewer dependencies, and about 1,370 fewer lines in package-lock.json.
  • Web Analytics and Speed Insights load only on production Vercel builds.

After that I fixed the rest of what Lighthouse flagged. That story is in Four 100s on PageSpeed Insights.