Add Vercel Analytics to Your Astro Website!

Although Vercel's main focus is Next.js — a React framework, they are generally very friendly to other projects. Their analytics can be used even in a static site like Astro!

Vojta Struhár
2 min readOct 25, 2023

I use Astro in its default SSG mode. But this will definitely work with server side rendering too!

1. Enable analytics on your Vercel project

Go to vercel.com and in the header of your project overview, click the little Analytics tab. You can enable your analytics there.

There are limits on the amount of data that can be logged for free. I'm of course on the Hobby tier, but I think this limit is plenty for my little personal website!

2. Install their analytics package

In your Astro project, install the vercel analytics package like you would any other.

pnpm i @vercel/analytics

3. Run analytics on your pages

Astro ships zero javascript by default. But you can explicitly include a script as HTML tag and it will work just fine!

I've put the following snippet into my root Layout.astro, which wraps all pages on my website. This way all pages are tracked! If you want to have analytics only for certain routes, add the snippet only there. But I generally think putting it in a layout component is a good idea.

<script>
import { inject } from "@vercel/analytics";
inject()
</script>

It’s that simple!

Note, that you have to import the function within the script tag itself. If you import it in the Astro frontmatter, the html won’t see it!

Don’t worry about the javascript cost

This script is absolutely tiny — it weights in at just ~1.1kB of javascript. Your users are not going to notice that. Smooth sailing!

Thanks for reading! ❤️ If you'd like to read more web development related tips, consider following!

--

--

Vojta Struhár

Always on the lookout for a smarter way to code. Mac enjoyer 🍎, Web developer 🕸️, Game developer 👾