Antoine Lehurt

Setting up Vercel Analytics in an Astro project

I have recently migrated my website to host it on Vercel. I was interested in experimenting with the analytics service that tracks Web Vitals. It’s not crucial for this lightweight static website—it even adds a JavaScript script—but I wanted to see what data we get from it.

It was straightforward to set up following the Astro documentation page:

  1. Install the dependency
pnpm add @astrojs/vercel
  1. Update the astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/static';

export default defineConfig({
  output: 'static',
  adapter: vercel({ analytics: true }),
});
  1. Enable Vercel Analytics in the project in the Vercel interface
  2. Deploy and profit!

Well, not yet for me—I got the error [Analytics] VERCEL_ANALYTICS_ID not found in the dev tools console.

When running the build command, the line const analyticsId = import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID got minified to e={}.PUBLIC_VERCEL_ANALYTICS_ID. To fix it, I needed define the custom variable in the astro.config.mjs to replace it with process.env.VERCEL_ANALYTICS_ID env var passed by Vercel on build time.

import vercel from '@astrojs/vercel/static';
import { defineConfig } from 'astro/config';

export default defineConfig({
  output: 'static',
  adapter: vercel({ analytics: true }),
  vite: {
    define: {
      'import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID': JSON.stringify(process.env.VERCEL_ANALYTICS_ID),
    },
  },
});

Alright, now it works!