Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
40 replies
Azuronate

Speed Insights for Astro

So on these docs: https://vercel.com/docs/speed-insights/quickstart

There is no dropdown for Astro, and Other is quite vague. What is the proper way for Astro projects to include Speed Insights for Vercel?
Vercel Documentation
Vercel Speed Insights provides you detailed insights into your website's performance. This quickstart guide will help you get started with using Speed Insights on Vercel.
Vercel Speed Insights Quickstart
Solution
UPDATE (December 20, 2023):

So with a little bit of digging, I've found an solution to the implementation for Vercel's Speed Insights via Astro. Even though it's not a drop down on their docs: https://vercel.com/docs/speed-insights/quickstart, the one your looking for is "Other frameworks"

Which consists of this code:
import { injectSpeedInsights } from '@vercel/speed-insights';
 
injectSpeedInsights();


Since Astro is styled as a MPA (Multi-Page Application) framework (as of Dec 2023) the equivalent to an App.jsx is your Layout.astro. Even though Astro says to put it in a main.ts I suggest putting it in the Layout.astro file.

With the confusion out of the way, here is steps to solving this issue.

STEPS: (Mostly from: https://vercel.com/docs/speed-insights/quickstart)
1. Enable Speed Insights
2. Install Vercel's Speed Insights: npm i @vercel/speed-insights
3. Add speedInsights to your astro.config.mjs NOT IN DOCS:
import { defineConfig } from 'astro/config';
import vercelStatic from '@astrojs/vercel/static';
 
export default defineConfig({
    output: 'static',
    adapter: vercelStatic({
        webAnalytics: {
            enabled: true,
        },
        speedInsights: {
            enabled: true,
        },
    }),
});

4. In a <script> tag in your Layout.astro put this code:
<script>
    import { injectSpeedInsights } from '@vercel/speed-insights';
    injectSpeedInsights({});
</script>

5. Deploy to production

Now you might be asking, King wtf this code is different from their example. Yes I know, apparently injectSpeedInsights requires an argument? Who knows, to fix that just put an empty object.

So far this is the solution that seems to work - good luck.
Was this page helpful?