withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.64k stars 2.47k forks source link

VERCEL_ANALYTICS_ID not found #7573

Closed pijusz closed 10 months ago

pijusz commented 1 year ago

What version of astro are you using?

2.7.4

Are you using an SSR adapter? If so, which one?

Vercel/Hybrid

What package manager are you using?

yarn

What operating system are you using?

Windows

What browser are you using?

Chrome

Describe the Bug

 "dependencies": {
    "@astrojs/vercel": "^3.6.0",
    "astro": "^2.7.4"
  }

config:

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

export default defineConfig({
  output: "static",
  adapter: vercel({
    analytics: true,
  }),
});

built script excerpt:

  const e = {}.PUBLIC_VERCEL_ANALYTICS_ID;
  if (!e) {
    console.error("[Analytics] VERCEL_ANALYTICS_ID not found");
    return;
  }

Once loading any website, there is console error "[Analytics] VERCEL_ANALYTICS_ID not found".

I've tried: different builds (static, hybrid, server)

What's the expected result?

There is no console error, and website reports to Vercel web vitals.

Link to Minimal Reproducible Example

https://molecular-sphere.vercel.app/

Participation

natemoo-re commented 1 year ago

There is definitely a history of this being an issue, perhaps there was a regression somewhere! Thanks for reporting.

https://github.com/withastro/astro/pull/6751

bluwy commented 1 year ago

Hmm that should be more thoroughly fixed at https://github.com/withastro/astro/pull/6876. How are you deploying your app? If it's handled by Vercel, it should populate the VERCEL_ANALYTICS_ID env var in build time. If you're deploying locally, you need to set the env var yourself.

pijusz commented 1 year ago

I've already sent the deployed example

General things: Plain Vercel/Astro deployment from github repo Analytics enabled on vercel, added config

pijusz commented 1 year ago

Adding the repo: https://github.com/pijusz/molecular-sphere

pijusz commented 1 year ago

Any progress on this one? I could try fixing it myself, but would need some ideas where I should even start.

bluwy commented 1 year ago

When I run the repro with VERCEL_ANALYTICS_ID=foobar pnpm build, I can see that it's being properly replaced. I guess my other hunch is that Vercel "intelligently" passes PUBLIC_VERCEL_ANALYTICS_ID instead because it knows we're using Astro. Could you help test this out by adding this in astro.config.mjs and deploying to Vercel?

console.log(process.env.VERCEL_ANALYTICS_ID, process.env.PUBLIC_VERCEL_ANALYTICS_ID)
if (!process.env.VERCEL_ANALYTICS_ID) {
 process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID
}
pijusz commented 1 year ago

Doesn't seem like fixed. If you do the build, the whole function that consumes the environment variable doesn't appear. image

pijusz commented 1 year ago

Vercel Analytics is behind on whole minor version (0.x.x : 0.1.x). Quite possible, that just updating it might work.

natemoo-re commented 1 year ago

Vercel Analytics is behind on whole minor version (0.x.x : 0.1.x). Quite possible, that just updating it might work.

I would expect this to help! We are a bit behind on dependency updates, so we'll try to give this a try

Aarekaz commented 1 year ago

image I am still not able to use it, Its giving me the same issue. Any fix?

Mrahmani71 commented 1 year ago

Try this @Aarekaz

define: {
    "import.meta.env.VITE_VERCEL_ANALYTICS_ID": JSON.stringify(process.env.VERCEL_ANALYTICS_ID),
    "import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID": JSON.stringify(process.env.VERCEL_ANALYTICS_ID),
},
dannyBies commented 1 year ago

Try this @Aarekaz

define: {
  "import.meta.env.VITE_VERCEL_ANALYTICS_ID": JSON.stringify(process.env.VERCEL_ANALYTICS_ID),
  "import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID": JSON.stringify(process.env.VERCEL_ANALYTICS_ID),
},

I've tried using this but unfortunately it doesn't work. I still get const e = {}.PUBLIC_VERCEL_ANALYTICS_ID;

bluwy commented 1 year ago

Maybe https://github.com/withastro/astro/pull/8021 would help address this, which noted:

It also threw an error when only Web Analytics was enabled since the environment variable for Speed Insights VERCEL_ANALYTICS_ID was not available.

The two features could be causing the confusion

ingomc commented 1 year ago

I was having the same problem, i switched analytics to webanalytics, i probably was following an old tutorial adapter: vercel({ webAnalytics: { enabled: true, },}),

ref-thomasledoux1 commented 11 months ago

FWIW, the comment from @bluwy fixed it for me. Add this to your astro.config.ts:

console.log(
  process.env.VERCEL_ANALYTICS_ID,
  process.env.PUBLIC_VERCEL_ANALYTICS_ID,
);
if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

My full astro.config.ts:

import { defineConfig } from "astro/config";
import tailwind from "@astrojs/tailwind";
import mdx from "@astrojs/mdx";
import { remarkReadingTime } from "./src/utils/calculate-reading-time.js";
import vercel from "@astrojs/vercel/serverless";
import react from "@astrojs/react";
import AutoImport from "astro-auto-import";
import {
  astroCodeSnippets,
  codeSnippetAutoImport,
} from "./integrations/astro-code-snippets";
import partytown from "@astrojs/partytown";

// https://astro.build/config
export default defineConfig({
  integrations: [
    tailwind({
      applyBaseStyles: false,
    }),
    react(),
    AutoImport({
      imports: [codeSnippetAutoImport],
    }),
    astroCodeSnippets(),
    partytown({
      config: {
        forward: ["dataLayer.push"],
      },
    }),
    mdx(),
  ],
  vite: {
    define: {
      "process.env.NODE_ENV": `'${process.env.NODE_ENV}'`,
    },
  },
  prefetch: {
    prefetchAll: true,
  },
  output: "hybrid",
  adapter: vercel({
    speedInsights: { enabled: true },
  }),
  markdown: {
    remarkPlugins: [remarkReadingTime],
  },
  site: "https://www.thomasledoux.be",
});

console.log(
  process.env.VERCEL_ANALYTICS_ID,
  process.env.PUBLIC_VERCEL_ANALYTICS_ID,
);
if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

Package versions: Astro version: 3.5.5 @astrojs/vercel: 5.2.0

kamontat commented 11 months ago

I found the problem why on my cases VERCEL_ANALYTICS_ID doesn't get correctly.

Current set up

I use GitHub Action to build package and publish package to Vercel for deployment using vercel cli. So my GitHub action will be something like below:

name: Deployment

on:
  push:

jobs:
  main:
    runs-on: ubuntu-latest
    env:
      VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
      VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
    steps:
      - uses: actions/checkout@v4
      - name: Set up pnpm
        uses: pnpm/action-setup@v2
      - name: Set up nodejs
        uses: actions/setup-node@v4
        with:
          node-version-file: "package.json"
          cache: "pnpm"
      - name: Pull environment information
        run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}
      - name: Build artifacts
        run: pnpm build
      - name: Deploy artifacts
        run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}

However, this doesn't works because vercel pull command doesn't pull VERCEL_ANALYTICS_ID variable.

vc pull does not pull VERCEL_ANALYTICS_ID as the Vercel Analytics ID environment variable is inlined during the build process. It is not part of your project Environment Variables, which can be pulled locally using Vercel CLI. ref: https://vercel.com/docs/speed-insights/api

BobidaHombre commented 10 months ago

FWIW, the comment from @bluwy fixed it for me. Add this to your astro.config.ts:

console.log(
  process.env.VERCEL_ANALYTICS_ID,
  process.env.PUBLIC_VERCEL_ANALYTICS_ID,
);
if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

My full astro.config.ts:

import { defineConfig } from "astro/config";
import tailwind from "@astrojs/tailwind";
import mdx from "@astrojs/mdx";
import { remarkReadingTime } from "./src/utils/calculate-reading-time.js";
import vercel from "@astrojs/vercel/serverless";
import react from "@astrojs/react";
import AutoImport from "astro-auto-import";
import {
  astroCodeSnippets,
  codeSnippetAutoImport,
} from "./integrations/astro-code-snippets";
import partytown from "@astrojs/partytown";

// https://astro.build/config
export default defineConfig({
  integrations: [
    tailwind({
      applyBaseStyles: false,
    }),
    react(),
    AutoImport({
      imports: [codeSnippetAutoImport],
    }),
    astroCodeSnippets(),
    partytown({
      config: {
        forward: ["dataLayer.push"],
      },
    }),
    mdx(),
  ],
  vite: {
    define: {
      "process.env.NODE_ENV": `'${process.env.NODE_ENV}'`,
    },
  },
  prefetch: {
    prefetchAll: true,
  },
  output: "hybrid",
  adapter: vercel({
    speedInsights: { enabled: true },
  }),
  markdown: {
    remarkPlugins: [remarkReadingTime],
  },
  site: "https://www.thomasledoux.be",
});

console.log(
  process.env.VERCEL_ANALYTICS_ID,
  process.env.PUBLIC_VERCEL_ANALYTICS_ID,
);
if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

Package versions: Astro version: 3.5.5 @astrojs/vercel: 5.2.0

Did this one, but now I have issue

POST https://vitals.vercel-analytics.com/v1/vitals 400 (Bad Request)

Anyone have some solution?

kamontat commented 10 months ago

FWIW, the comment from @bluwy fixed it for me. Add this to your astro.config.ts:

@BobidaHombre The @bluwy fix doesn't fix the problem. It just hide the problem.

if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

This code only works if PUBLIC_VERCEL_ANALYTICS_ID has a valid value. if not, it will pass normally but not able to send metrics.

@BobidaHombre You need to check is dsn value is correctly place or not. The value should be some random string (as image shown).

CleanShot 2023-12-28 at 10 39 44@2x

BobidaHombre commented 10 months ago

FWIW, the comment from @bluwy fixed it for me. Add this to your astro.config.ts:

@BobidaHombre The @bluwy fix doesn't fix the problem. It just hide the problem.

if (!process.env.VERCEL_ANALYTICS_ID) {
  process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID;
}

This code only works if PUBLIC_VERCEL_ANALYTICS_ID has a valid value. if not, it will pass normally but not able to send metrics.

@BobidaHombre You need to check is dsn value is correctly place or not. The value should be some random string (as image shown).

CleanShot 2023-12-28 at 10 39 44@2x

Yup, this is an issue. dsn in my requests are undefined

alexkazachkov commented 10 months ago

I have the same issue with the direct Astro integration.

Using console.log( process.env.VERCEL_ANALYTICS_ID, process.env.PUBLIC_VERCEL_ANALYTICS_ID, ); if (!process.env.VERCEL_ANALYTICS_ID) { process.env.VERCEL_ANALYTICS_ID = process.env.PUBLIC_VERCEL_ANALYTICS_ID; }

helped to get the vitals on the page loading, but I got the same 400 error, with this message: { "statusCode": 400, "error": "Bad Request", "message": "body/dsn must NOT have fewer than 25 characters" }

Then I had a look at the Vercel build and got this warning for Vercel CLI 33.0.1: WARN! TheVERCEL_ANALYTICS_IDenvironment variable is deprecated and will be removed in a future release. Please remove it from your environment variables

Then I found this page: https://vercel.com/docs/speed-insights/api

Here is written: This API is deprecated. Use the @vercel/speed-insights framework agnostic package instead.

I suppose the Vercel Speed Insights package has to be updated in Astro.

But the Speed Insights package from Vercel also got an update for direct Astro support. I tried it out now, and it works:

https://github.com/vercel/speed-insights

I used this info to get it working: https://github.com/vercel/speed-insights/blob/main/apps/astro/src/components/BaseHead.astro

But it still shows this warning for the Vercel builds: WARN! TheVERCEL_ANALYTICS_IDenvironment variable is deprecated and will be removed in a future release. Please remove it from your environment variables

Edit 7 hours later: For some reason with the direct implementation from the Vercel Speed Insights GitHub project, there is no vitals network request which should be in the network tab. Also, I don't get any Real Experience Score (RES), which might also have something to do with vitals not loading.

But every other metric shows up.

Edit once more: never mind, just needed more data. The RES now shows up. But vitals in the network tab doesn't. Maybe it doesn't have to, I don't know.

lilnasy commented 10 months ago

Thanks for looking into it, @alexkazachkov!

Considering that the API we are using is deprecated, we can remove it along with all mentions of VERCEL_ANALYTICS_ID from the codebase which should address the warnings.

Regarding vitals missing, since the new package does not require involvement from the framework, it can be reported directly at vercel/speed-insights.

KingPr0o7 commented 10 months ago

Hmm, it seems that people are also seeing this issue. I'm using Astro and here's everything I've done:

astro.config.mjs:

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

export default defineConfig({
    output: 'static',
    adapter: vercelStatic({
        webAnalytics: {
            enabled: true,
        },
        speedInsights: {
            enabled: true,
        },
    }),
});

From: https://docs.astro.build/en/guides/integrations-guide/vercel/#speed-insights

package.json:

  "dependencies": {
    "@astrojs/vercel": "^6.1.0",
    "@vercel/analytics": "^1.1.1",
    "@vercel/speed-insights": "^1.0.2",
    "astro": "^4.0.7"
  }

Layout.astro:

<script>
    import '../nav.js';

    import { injectSpeedInsights } from '@vercel/speed-insights';
    try {
        injectSpeedInsights({});
    } catch (error) { // Will remove when Vercel fixes this :/
        if (!error.message.includes('VERCEL_ANALYTICS_ID not found')) {
            throw error;
        }
    }
</script>

Mostly from: https://vercel.com/docs/speed-insights/quickstart#add-@vercel/speed-insights-to-your-project (Other Frameworks > TS) && https://github.com/vercel/speed-insights/issues/32.

Tried to catch the error because I do see Speed Insights on my panel like this: My Vercel Speed Insights

For some reason, I sometimes do see both the script.js and the vitals: My Network Tab As @kamontat mentioned, with dsn... I don't have one (Probably from implementation). Although to see vitals it's either on a lucky reload or waiting a while: Vitals after 110000ms

Yet with all of that, I get this console error: Vercel Speed Insight's Analytics ID not found

Now @lilnasy mentioned it's something to do with the deprecation of the old API. Which might be a big factor towards this. Also don't know if I should've posted this somewhere else... please let me know if I should.

alexkazachkov commented 10 months ago

Hello @KingPr0o7,

Could you please, if you have time, try out the approach I suggested, to move just the Speed Insights to the native Vercel Astro package?

Here are the two links on how to do that: https://github.com/vercel/speed-insights https://github.com/vercel/speed-insights/blob/main/apps/astro/src/components/BaseHead.astro

Your dependencies are already up-to-date, so that's good. You just have to disable Speed Insights in your Astro config:

speedInsights: { enabled: false, },

And then import this in your head part of your layout:

---
import SpeedInsights from '@vercel/speed-insights/astro';

[Your other code]
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    [...]
    <script is:inline>
      function speedInsightsBeforeSend(data){
        console.log("Speed Insights before send", data)
        return data;
      }
    </script>

    <SpeedInsights />

  </head>

And then you can message here again, if this removes the error from your page loads.

KingPr0o7 commented 10 months ago

@alexkazachkov, with a deeper look into your solution (which admittedly I should've tried beforehand) it does indeed remove the error. Although this solution is a bit hacky, it does get the job done.

The only thing (that will probably be fixed later) I noticed with this solution is: Vercel's Speed Insights for Astro Package not recognized Thankfully which didn't stop the building of the deployment.

Now my question is: Is there a plan to instate a cleaner solution as thus such:

---
import SpeedInsights from '@vercel/speed-insights/astro';
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <SpeedInsights />
  </head>
</html>
alexkazachkov commented 10 months ago

@KingPr0o7 It's okay. Happy New Year, by the way.

I actually don't have the error you describe. For me it's not saying that the module can't be found. So I'm not sure where the issue is in your project.

My import looks like this:

---
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";

import SpeedInsights from "@vercel/speed-insights/astro";

My dependencies:

"dependencies": {
    "@astrojs/vercel": "^6.1.1",
    "@botpoison/node": "^0.1.10",
    "@imgix/js-core": "^3.8.0",
    "@vercel/analytics": "^1.1.1",
    "@vercel/speed-insights": "^1.0.2",
    "astro": "^4.0.8",
    "astro-remote": "^0.2.4",
    "autoprefixer": "^10.4.16",
    "cssnano": "^5.1.14",
    "luxon": "^3.4.4",
    "prettier": "^2.8.7",
    "prettier-plugin-astro": "^0.8.0",
    "resend": "^2.0.0",
    "sanitize-html": "^2.11.0",
    "sass": "^1.69.5",
    "scss": "^0.2.4",
    "sharp": "^0.32.6",
    "vercel": "^33.0.1"
  }

So although you have "@vercel/speed-insights": "^1.0.2" as well, you might want to try to npm uninstall and install it again?

KingPr0o7 commented 10 months ago

@alexkazachkov Hmm that's weird. Removed and reinstalled it, hopefully @lilnasy's pull request will solve this.

lilnasy commented 10 months ago

To clarify, my PR does not change anything. It marks the speedInsights config as deprecated. The code paths related to it were the only parts using VERCEL_ANALYTICS_ID.

I'd recommend migrating to the vercel library.

https://vercel.com/docs/speed-insights/quickstart