Code Monkey home page Code Monkey logo

analytics's Introduction

Analytics

Vercel Web Analytics
Privacy-friendly, real-time traffic insights

Overview

@vercel/analytics allows you to track page views and custom events in your Next.js app or any other website that is deployed to Vercel.

All page views are automatically tracked in your app.

This package does not track data in development mode.

Quickstart

  1. Enable Vercel Web Analytics for a project in the Vercel Dashboard.

  2. Add the @vercel/analytics package to your project

  3. Inject the Analytics script to your app

    • If you are using Next.js or React, you can use the <Analytics /> component to inject the script into your app.
    • To add the tracking script for other frameworks, use the inject function.
    • If you want to use Vercel Web Analytics on a static site without npm, follow the instructions in the documentation.
  4. Deploy your app to Vercel and see data flowing in.

Documentation

Find more details about this package in our documentation.

analytics's People

Contributors

acao avatar andybitz avatar chriswdmr avatar dglsparsons avatar ethan-arrowood avatar feugy avatar macielg1 avatar maxleiter avatar paoloricciuti avatar timolins avatar tobiaslins avatar tootallnate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

analytics's Issues

Development mode is incorrect in vite dev

Summary

In a browser accessing a Vite dev server, the value of isDevelopment() is false.

Therefore /_vercel/insights/script.js is requested, resulting in a 404 Not Found.

Reason

In a browser accessing a Vite dev server, the process is undefined.

export function isDevelopment(): boolean {
if (typeof process === 'undefined') return false;
return (
process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'
);
}

Therefore isDevelopment() returns false.

Reproduction

Open the browser console to see what is logged in the client inside StackBlitz.

Values

In a browser accessing a Vite dev server:

SvelteKit Next.js
isBrowser() true true
isDevelopment() false * true
typeof process undefined * object
typeof process.env.NODE_ENV string string
process.env.NODE_ENV development development

Custom events from routes / SSR

The documentation for custom events states:

It’s important to note that custom events can only be tracked on the client-side. Server-side events are not currently supported by Vercel Web Analytics.

Are server-side custom events on the roadmap? Or would you recommend an alternative approach? I know of a lot of the popular alternatives like Datadog and NewRelic, but I'd love to use a simpler integrated solution.

Thanks for all you folks do!

Add `Cross-Origin-Resource-Policy: cross-origin` header to CDN asset to support sites with COEPs

Currently the Analytics debug script (script.debug.js) gets blocked on development environment when the site has a Cross-Origin Embedder Policy with a require-corp value. (e.g. Required for enabling APIs that require site isolation such as SharedArrayBuffer)

GET https://cdn.vercel-insights.com/v1/script.debug.js 
net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200

The fix usually involves simply adding Cross-Origin-Resource-Policy: cross-origin header to the resource served from the CDN.

More information about COEPs, COOPs and CORPs: https://web.dev/coop-coep/

Note: Most likely low priority, given the script is proxied on production environment and hence served from the same origin.

const src =
mode === 'development'
? 'https://cdn.vercel-insights.com/v1/script.debug.js'
: '/_vercel/insights/script.js';

Adding Analytics wrecks Fonts

I have a simple next.js /app setup. I am using google fonts following the guidance in the docs.

import { Odibee_Sans, Ubuntu } from '@next/font/google';
import GridHeader from './GridHeader';
import styles from './globals.css';
import GridRightHeader from './GridRightHeader';
import Footer from './footer';
import ScrollToTop from '@/components/ScrollToTop';

const obidee_sans = Odibee_Sans({
    subsets: ['latin'],
    weight: ['400'],
    variable: '--font-obidee-sans',
    display: 'optional',
});

const ubuntu = Ubuntu({
    subsets: ['latin'],
    weight: ['400'],
    variable: '--font-ubuntu',
    display: 'optional',
});

export default function RootLayout({ children }) {
    return (
        <html lang="en" className={`${obidee_sans.variable} ${ubuntu.variable}`}>
            {/*
        <head /> will contain the components returned by the nearest parent
        head.jsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
      */}
            <head />
            <body>
                <div className="app_grid" id="root">
                    <ScrollToTop />
                    <GridHeader />
                    <GridRightHeader />
                    <div id="app_grid_content" className="app_grid_content">
                        {children}
                        <Footer />
                    </div>
                </div>
            </body>
        </html>
    );
}

I added Analytics to my project, but the moment I add it to my layout, the fonts stop loading.

import { Analytics } from '@vercel/analytics/react';
import { Odibee_Sans, Ubuntu } from '@next/font/google';
import GridHeader from './GridHeader';
import styles from './globals.css';
import GridRightHeader from './GridRightHeader';
import Footer from './footer';
import ScrollToTop from '@/components/ScrollToTop';

const obidee_sans = Odibee_Sans({
    subsets: ['latin'],
    weight: ['400'],
    variable: '--font-obidee-sans',
    display: 'optional',
});

const ubuntu = Ubuntu({
    subsets: ['latin'],
    weight: ['400'],
    variable: '--font-ubuntu',
    display: 'optional',
});

export default function RootLayout({ children }) {
    return (
        <html lang="en" className={`${obidee_sans.variable} ${ubuntu.variable}`}>
            {/*
        <head /> will contain the components returned by the nearest parent
        head.jsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
      */}
            <head />
            <body>
                <div className="app_grid" id="root">
                    <ScrollToTop />
                    <GridHeader />
                    <GridRightHeader />
                    <div id="app_grid_content" className="app_grid_content">
                        {children}
                        <Footer />
                        <Analytics />
                    </div>
                </div>
            </body>
        </html>
    );
}
`

That's literally the only change in my project.  You can just add/remove the Analytics call and the fonts flip back and forth.  Any idea what is going on?  I'm literally just following the docs for both fonts and analytics, but you put them together and it ain't no worky.

TypeError: Cannot read properties of null (reading 'useEffect') [Next.JS v13.4.0]

Problem

Adding <Analytics /> causes the build to break on vercel.com

I am trying to understand this, but running the build locally (next build) works great. When I push my changes up into GitHub / Vercel, the build breaks. For every page listed under the /pages directory I get the error:

Error occurred prerendering page "/my-page". Read more: https://nextjs.org/docs/messages/prerender-error
--
15:38:49.692 | TypeError: Cannot read properties of null (reading 'useEffect')
15:38:49.692 | at exports.useEffect (/vercel/path0/node_modules/react/cjs/react.production.min.js:24:292)
15:38:49.692 | at Analytics (file:///vercel/path0/node_modules/@vercel/analytics/src/react.tsx:33:3)
15:38:49.692 | at Ge (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:114:273)
15:38:49.692 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:91)
15:38:49.693 | at He (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:123:155)
15:38:49.693 | at Je (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:122:100)
15:38:49.693 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:222)
15:38:49.693 | at He (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:123:155)
15:38:49.693 | at Ge (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:115:215)
15:38:49.694 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:91)
15:38:49.696 | TypeError: Cannot read properties of null (reading 'useEffect')
15:38:49.696 | at exports.useEffect (/vercel/path0/node_modules/react/cjs/react.production.min.js:24:292)
15:38:49.697 | at Analytics (file:///vercel/path0/node_modules/@vercel/analytics/src/react.tsx:33:3)
15:38:49.697 | at Ge (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:114:273)
15:38:49.697 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:91)
15:38:49.697 | at He (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:123:155)
15:38:49.697 | at Je (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:122:100)
15:38:49.697 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:222)
15:38:49.697 | at He (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:123:155)
15:38:49.698 | at Ge (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:115:215)
15:38:49.698 | at Z (/vercel/path0/node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js:120:91)

I have tried listing the <Analytics /> in both the _app.tsx and _document.tsx, but neither location seem to work.

Any ideas?

Referrers panel seems to not be getting data

I have implemented Vercel Web Analytics on my personal website (https://github.com/bartvdbraak/hellob.art)

However, I don't seem to be getting any referrer data for it. If I inspect the API calls being made, they look as follows:

curl 'https://hellob.art/_vercel/insights/view' \
  --data-raw '{"o":"https://hellob.art/?ref=github","sv":"0.1.2","sdkn":"@vercel/analytics","sdkv":"1.0.1","ts":1690662958930,"r":"https://github.com/"}' \
  --compressed

Even when I am coming from GitHub, which does populate the Referer header on my first document GET request:

curl 'https://hellob.art/?ref=github' \
  --compressed \
  -H 'Referer: https://github.com/'

What is Vercel using to gain these data points? Am I doing it wrong?

Facing issues while deploying frontend on vercel


npm ERR! code ERESOLVE
--
03:31:21.268 | npm ERR! ERESOLVE could not resolve
03:31:21.268 | npm ERR!
03:31:21.268 | npm ERR! While resolving: [email protected]
03:31:21.268 | npm ERR! Found: @typescript-eslint/[email protected]
03:31:21.268 | npm ERR! node_modules/@typescript-eslint/eslint-plugin
03:31:21.268 | npm ERR!   dev @typescript-eslint/eslint-plugin@"^5.59.0" from the root project
03:31:21.268 | npm ERR!
03:31:21.268 | npm ERR! Could not resolve dependency:
03:31:21.269 | npm ERR! peer @typescript-eslint/eslint-plugin@"^4.0.0" from [email protected]
03:31:21.269 | npm ERR! node_modules/eslint-config-react-app
03:31:21.269 | npm ERR!   dev eslint-config-react-app@"^6.0.0" from the root project
03:31:21.269 | npm ERR!
03:31:21.269 | npm ERR! Conflicting peer dependency: @typescript-eslint/[email protected]
03:31:21.269 | npm ERR! node_modules/@typescript-eslint/eslint-plugin
03:31:21.269 | npm ERR!   peer @typescript-eslint/eslint-plugin@"^4.0.0" from [email protected]
03:31:21.269 | npm ERR!   node_modules/eslint-config-react-app
03:31:21.269 | npm ERR!     dev eslint-config-react-app@"^6.0.0" from the root project
03:31:21.269 | npm ERR!
03:31:21.270 | npm ERR! Fix the upstream dependency conflict, or retry
03:31:21.270 | npm ERR! this command with --force or --legacy-peer-deps
03:31:21.270 | npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
03:31:21.270 | npm ERR!
03:31:21.270 | npm ERR!
03:31:21.270 | npm ERR! For a full report see:
03:31:21.270 | npm ERR! /vercel/.npm/_logs/2023-07-22T22_01_20_300Z-eresolve-report.txt
03:31:21.271 |  
03:31:21.271 | npm ERR! A complete log of this run can be found in:
03:31:21.271 | npm ERR!     /vercel/.npm/_logs/2023-07-22T22_01_20_300Z-debug-0.log
03:31:21.288 | Error: Command "npm install" exited with 1

This is the package.json file

{
  "name": "parametriks_insights",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@mui/icons-material": "^5.11.16",
    "@mui/material": "^5.13.6",
    "@mui/x-data-grid": "^6.9.0",
    "@reduxjs/toolkit": "^1.9.5",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.1.1",
    "react-router-dom": "^6.14.0",
    "recharts": "^2.7.2",
    "regression": "^2.0.1"
  },
  "devDependencies": {
    "@types/node": "^20.3.1",
    "@types/react": "^18.0.37",
    "@types/react-dom": "^18.2.6",
    "@typescript-eslint/eslint-plugin": "^5.59.0",
    "@typescript-eslint/parser": "^5.59.0",
    "@vitejs/plugin-react": "^4.0.0",
    "eslint": "^8.43.0",
    "eslint-config-react-app": "^6.0.0",
    "eslint-import-resolver-typescript": "^3.5.5",
    "eslint-plugin-import": "^2.27.5",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.3.4",
    "typescript": "^5.0.2",
    "vite": "^4.3.9"
  }
}

How to resolve this issue? Thanks

My analytics aren't working, is my HOC the main reason?

Hello fellas, a few days ago I deployed my Project, but seems analytics don't work. If you try to open the debugger options, you can't see the script at /_vercel/insights/script.js

The only thing that maybe is causing trouble could be the appWithTranslation 🤔

code

Of course, Vercel is waiting for:
image

Question: More event types, what to expect, when?

Hello,

can you share some estimation/development timeline of what the Vercel users can expect from the Analytics/Audiences feature?
I am struggling now because Splitbee sign-ups are now closed, but Vercel's Audience feature seems limited; for example, only PageView events are currently supported.

It seems if I want to start a new project, I need to find another analytics provider to be able to track simple button clicks.
Is it possible that other events will be supported this year and wait a little bit, or is this a much bigger effort?

thanks in advance! ❤️

My domain/website is showing as a referrer in its own analytics dashboard

This started to happen today where I noticed that my own domain is showing as a referrer in "Top referrers" list. That can't be right?

Don't know what could be a cause, didn't do any obvious changes to my page.

Also I noticed that when I click on a link to filter by my own domain as referrer it shows zero results, also the links are broken with double protocol string when hovering above those links https://https// inside of the same analytics pane.

If needed I can provide an URL to my project if you wanna check directly on the backend.

Docs - AdBlockers & reverse proxy?

When your audience is mainly developers and people related to IT industry you are "losing" a lot of data.
A lot of people use AdBlockers, (in IT industry more than ~80%, overall ~40%), so this script is blocked - therefore you get no data and visitor count is not accurate.

A solution to this is using some sort of reverse proxy.
Is this possible with Vercel Analytics?

PS. This is also accurate to Vercel Insights.

Vercel analytics data much higher than another analytics

Hi, I wonder how Vercel Analytics calculates visitors and pageviews. I test with Vercel and it got 7k visitors and 70k pageviews per day but with Fathom or Google Analytics (the data of both platforms is quite similar) I just got 4k5 visitors and 40k pageviews... why is it so different?

Bug: all type imports not explicitly defined. `moduleResolution` setting required to import all types

moduleResolution NodeNext only allows defined import paths

moduleResolution: NodeNext

only allows defined import paths

When setting moduleResolution in tsconfig.json to NodeNext. When this is enabled, the module resolution will only allow importing from paths that are defined within the exports config. Because only types/index.d.ts is available for import, it can cause these kinds of embedded imports to fail:

'use client';
import { Analytics } from '@vercel/analytics/react';
'use client';
import { Analytics } from '@vercel/analytics/react';

export function AnalyticsWrapper() {
  return <Analytics />;
}

VSCode

Screenshot 2023-07-06 at 4 24 17 PM

Solution

Document this tsconfig requirement. An alternative would be to ensure that all types are exported from the types/index.d.ts file.

Usage in redirect routes

Hi, thanks for providing this convenient SDK and I enjoy using it in my Next.js projects. I'm just wondering how am I supposed to use it in routes that redirects (so that the <Analytics /> component won't render)? FYI in my case I'm doing redirects in getServerSideProps, and I want to track visitors and views to this /some-route path.

// pages/some-route.js

export async function getServerSideProps() {
  if (await shouldRedirect()) {
    return {
      destination: 'https://my.destination',
      permanent: false
    }
  }

  return {
    props: {}
  }
}

404 error in nuxt3 about _vercel/insights/script.js

Fix:

Option 1: In node_modules/@vercel/analytics/analytics/dist/index.js,

Or better, option 2:

Last step

In nuxt3 create the following plugin-file:

~/plugins/vercel.client.ts

import { inject } from '@vercel/analytics'

export default defineNuxtPlugin((/* nuxtApp */) => {
  // nuxtApp.provide('inject', () => inject() ) // Not working, using return instead.

  return {
    provide: {
      inject: inject()
    }
  }
})

/*
sources:
https://vercel.com/docs/concepts/analytics/quickstart
https://vercel.com/blog/nuxt-analytics-on-vercel
https://nuxt.com/docs/migration/plugins-and-middleware
https://vercel.com/lovkyndig/eleison/analytics // login to activate analytics

Read about the fix in 
https://github.com/vercel/analytics/issues/84
*/

My GitHub-repo with this code is here: Eleison

Feature request: Treat i18n path segments as a separate dimension from page paths

My site uses next.js's i18n support in the sub-path routing configuration. The locale path segment is causing the new Audiences feature to treat different locales as different pages, which isn't very helpful.

My top pages looks like this:

/compare
/en/compare
/
/en-GB/compare
/en
/de-DE/compare
/en-GB
/about
/de-DE
/en/about

It'd be great to have some way to collapse these locales into a single entry in Audiences. e.g.:

/compare
/
/about

As a bonus, if the locale could be treated as a separate dimension then it would be cool to have a pane with a breakdown of visitors by locale.


I'm excited to see Vercel investing in this area! Thanks!

Refused to execute script

I just added this to my site but when I visit it this error gets logged:
Refused to execute script from 'https://alexanderkonietzko-84q9dz1ke-alex289.vercel.app/va/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Does this happen because I have X-Content-Type-Options: nosniff enabled?

Here is my repo for more information

BeforeSend don't work in app directory RSC

When using beforeSend in my root layout it throws this error

 
1 of 1 unhandled error

Unhandled Runtime Error
Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".
  <... beforeSend={function}>
                  ^^^^^^^^^^
                  
                  ```

Error: Cannot find module 'private-next-rsc-mod-ref-proxy'

When following instructions (https://vercel.com/docs/concepts/analytics/quickstart) to add Vercel analytics, I'm getting this error:

error - Error: Cannot find module 'private-next-rsc-mod-ref-proxy'
Require stack:
- /Users/zhangela/projects/dispatch/website/.next/server/app/page.js
- /Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/require.js
- /Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/load-components.js
- /Users/zhangela/projects/dispatch/website/node_modules/next/dist/build/utils.js
- /Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/dev/static-paths-worker.js
- /Users/zhangela/projects/dispatch/website/node_modules/next/dist/compiled/jest-worker/processChild.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at mod._resolveFilename (/Users/zhangela/projects/dispatch/website/node_modules/next/dist/build/webpack/require-hook.js:23:32)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at eval (webpack-internal:///(sc_server)/./node_modules/@vercel/analytics/dist/react/index.js:2:74)
    at (sc_server)/./node_modules/@vercel/analytics/dist/react/index.js (/Users/zhangela/projects/dispatch/website/.next/server/app/page.js:2529:1)
    at __webpack_require__ (/Users/zhangela/projects/dispatch/website/.next/server/webpack-runtime.js:33:43)
    at eval (webpack-internal:///(sc_server)/./app/layout.tsx:8:81)
    at (sc_server)/./app/layout.tsx (/Users/zhangela/projects/dispatch/website/.next/server/app/page.js:665:1) {
  type: 'Error',
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/zhangela/projects/dispatch/website/.next/server/app/page.js',
    '/Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/require.js',
    '/Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/load-components.js',
    '/Users/zhangela/projects/dispatch/website/node_modules/next/dist/build/utils.js',
    '/Users/zhangela/projects/dispatch/website/node_modules/next/dist/server/dev/static-paths-worker.js',
    '/Users/zhangela/projects/dispatch/website/node_modules/next/dist/compiled/jest-worker/processChild.js'
  ],
  page: '/'
}

and this warning:

Attempted import error: 'Analytics' is not exported from '@vercel/analytics/react' (imported as 'Analytics').

Relevant package.json:

        "@vercel/analytics": "^1.0.1",
        "next": "13.0.8-canary.0",

layout.tsx:


import { Inter } from "@next/font/google";

import "../styles/globals.css";

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-inter",
});

export default function DotComLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en" className={`${inter.variable} h-full scroll-smooth`}>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  );
}

Request Bodies with "o" Object Should be Encoded

Overview

I'm assuming this is the correct repo to write an issue found within /_vercel/insights/script.js. If not please let me know or point me in the right direction.

in script.js we make a fetch call to /_vercel/insights/ endpoints like so

await fetch(`${n}/${"pageview" === i ? "view" : "event"}`, {
           method: "POST",
           keepalive: !0,
           headers: {
               "Content-Type": "application/json"
           },
           body: JSON.stringify(f)
       })

however the body f is defined by

f = {
       o: d,
       sv: "0.1.2",
       sdkn: null != (r = null == t ? void 0 : t.getAttribute("data-sdkn")) ? r : void 0,
       sdkv: null != (l = null == t ? void 0 : t.getAttribute("data-sdkv")) ? l : void 0,
       ts: Date.now(),
       ...null != a && a.withReferrer && !s ? {
           r: u
       } : {},
       ..."event" === i && o && {
           en: o.name,
           ed: o.data
       }
   };

and d = location.href. The reason this is an issue is the /_vercel/insights/ endpoints seem to anticipate that o is already encoded, and if its not returns an error that looks like
{"statusCode":400,"error":"Bad Request","message":"body/href must match format \"uri\""}.

If you want to see evidence of this error you can search "vercel" requests in dev tools -> network when visiting a page like

https://www.ifixit.com/products/galaxy-note10-plus-replacement-battery?exampleVercelError={hello}

whereas
https://www.ifixit.com/products/galaxy-note10-plus-replacement-battery?exampleVercelError=hello has those vercel calls work fine.

Proposed Solution

I think that body: JSON.stringify(encodeURI(f)) should solve this issue, or maybe getting the uri and then running encodeURIComponent on the params etc. Or if you have access to the vitals API endpoints code you can make it encode expected URIs on the server side, because I notice the same error occurring for the body key-value href for calls to
https://vitals.vercel-insights.com/v1/vitals

Analytics treats in-page anchor jumps as pageviews

There seems to be a potential bug in /_vercel/analytics/script.js:

history.pushState = function(...t) {
    let n = t[2]
      , i = "string" == typeof n ? location.pathname !== n.split("?")[0] : n && location.href !== n.href;
    e(...t),
    i && r()
}

It is comparing pathname with the target URL apart from the search part. But for target URLs like /foo#bar it will be count as a new page view. And I'm also aware that if we strip hashes as well this may break the use case for those SPAs with hash router. So I think we should expose an option to let users to configure their routing behavior.

Feature request: REST API

I know this just launched on Vercel, but I'm curious if there will be an API to query page views and events... ideally w/ SQL? Let me know if there's a better place to ask this too.

Module not found: Can't resolve 'react'

Hello,

I did the example from the docs:
yarn add @vercel/analytics
During install get warning " > @vercel/[email protected]" has unmet peer dependency "react@^16.8||^17||^18".
And after installing and putting in _app.tsx:

import { Analytics } from '@vercel/analytics/react';

I got error:
Screenshot 2022-10-29 at 20 40 43

Here is my package.json:

{
  "private": true,
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "typecheck": "tsc",
    "prepare": "husky install"
  },
  "dependencies": {
    "@microflash/remark-figure-caption": "^1.0.0",
    "@wooorm/starry-night": "^1.1.0",
    "classnames": "2.3.1",
    "date-fns": "2.21.3",
    "gray-matter": "4.0.3",
    "hast-util-to-string": "^2.0.0",
    "next": "^12.1.6",
    "prettier": "^2.5.1",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "rehype-document": "^6.0.1",
    "rehype-format": "^4.0.1",
    "rehype-highlight": "^5.0.2",
    "rehype-stringify": "^9.0.3",
    "remark": "14.0.2",
    "remark-rehype": "^10.1.0",
    "typescript": "^4.2.4"
  },
  "devDependencies": {
    "@types/jest": "^26.0.23",
    "@types/node": "^15.6.0",
    "@types/react": "^18.0.12",
    "@types/react-dom": "^18.0.5",
    "autoprefixer": "10.4.0",
    "eslint": "8.17.0",
    "eslint-config-next": "12.1.6",
    "eslint-config-prettier": "^8.5.0",
    "husky": "^8.0.0",
    "lint-staged": "^13.0.1",
    "postcss": "8.4.5",
    "tailwindcss": "3.0.5"
  }
}

TypeError: Cannot read properties of undefined (reading 'Analytics') with NextJS 13.0.0

Problem

When following the Quickstart instructions for Vercel Audiences, building my NextJS (13.0.0) project results in an error when running next build:

> next build

warn  - You have enabled experimental feature (appDir) in next.config.js.
warn  - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.
info  - Thank you for testing `appDir` please leave your feedback at https://nextjs.link/app-feedback

info  - Creating an optimized production build
info  - Compiled successfully
info  - Linting and checking validity of types
info  - Collecting page data
[    ] info  - Generating static pages (0/3)

TypeError: Cannot read properties of undefined (reading 'Analytics')
    at Oa (.next/server/chunks/759.js:1025:56)
    at Ia (.next/server/chunks/759.js:1138:50)
    at Array.toJSON (.next/server/chunks/759.js:915:32)
    at stringify (<anonymous>)
    at S (./.next/server/chunks/759.js:1213:51)
    at Object.start (.next/server/chunks/759.js:1324:53)
    at setupReadableByteStreamController (node:internal/webstreams/readablestream:2665:23)
    at setupReadableByteStreamControllerFromSource (node:internal/webstreams/readablestream:2702:3)
    at new ReadableStream (node:internal/webstreams/readablestream:240:7)
    at exports.renderToReadableStream (.next/server/chunks/759.js:1321:24)

[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '3412299338'
}

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read properties of undefined (reading 'Analytics')

Minimum reproducible example

I can reproduce this by:

  1. Running pnpm create next-app
  2. Setting the NextJS version to 13.0.0 in the package.json
    a. pnpm install again to install 13.0.0
    b. remove the exported metadata constant from layout.tsx which wasn't supported in NextJS 13.0.0
    c. remove the import { Inter } from 'next/font/google' from page.tsx
  3. Follow the Quickstart Guide for NextJS 13 with the Analytics tag in the /app directory.
  4. Run pnpm run build which should fail with the above error!

The fix

I updated my NextJS version to "next": "13.2.4",!

I couldn't find any other issues relating to this or mention in the docs (<Analytics /> only working for given versions of NextJS) - hopefully posting the issue helps!

Nextjs Optional Catch-All route at the Root level is intercepting `_vercel/insights/script.js`

As the title suggests, when using an Optional Catch-All route (pages/[[,,,sllug]].tsx), network requests for _vercel/insights/script.js are unexpectedly intercepted by the dynamic route handler, resulting in this script not loading on the page.

Here is an example sandbox reproduction:

https://codesandbox.io/p/sandbox/empty-microservice-0li06m?file=%2FREADME.md&selection=%5B%7B%22endColumn%22%3A136%2C%22endLineNumber%22%3A11%2C%22startColumn%22%3A136%2C%22startLineNumber%22%3A11%7D%5D

Please follow along with the readme there for instructions to view this error in your browser.

If there is a workaround for this category of errors with optional catch-all routes, it would be excellent if the docs included more information on how to handle this situation. I can open an issue in the Nextjs repo instead if that would be a better place for this.

Performance issue with latest nextjs 13

The app is deployed on Vercel normally, but when loading the app, there is a script file that loads for 1+ sec. Here is screenshot

Screenshot 2022-10-30 at 21 26 54

When I removed analytics package, website loaded much faster and FCP was much lower.

Subdomain analytics

For openstatus we allow users to create subdomain hosted under our own domain

They are rewritten using next middleware

Is it possible to track this subdomain ?
Maybe with before send function?

Does the event contains the full request hostname ?

NextJS App won't build with `pnpm`

Hey folks! I've followed the quickstart instructions, but am presented with this error when building our app with pnpm on Github Actions:

image

What info can I provide to help reproduce this issue?

ESLint: Unable to resolve path to module '@vercel/analytics/react' (import/no-unresolved)

Steps to reproduce:

Expected behavior:

  • Deployment is successful

Actual behavior:

  • Deployment fails:
2022-11-17T04:00:34.842Z  Failed to compile.
2022-11-17T04:00:34.842Z
2022-11-17T04:00:34.842Z  ./pages/_app.tsx
2022-11-17T04:00:34.843Z  10:27  Error: Unable to resolve path to module '@vercel/analytics/react'.  import/no-unresolved

Workaround:

  • Add // eslint-disable-next-line import/no-unresolved before import { Analytics } from "@vercel/analytics/react";.

Version:
0.1.5

This is also as described in https://stackoverflow.com/a/74453475/2736037.

HTTP 404 error for /_vercel/insights/script.js

I added the Vercel Web Analytics to my project. I enabled the feature on Vercel project dashboard, installed the package and initialized the package inside my project but I'm getting an HTTP 404 error for /_vercel/insights/script.js. My site is proxied through Cloudflare. Is there any special configuration needed other than what was documented here?

I have automatic deployments to Vercel from Github commits. I have also added in my Content Security Policy the domains;

I saw a similar issue but there wasn't any resolution provided. I can provide my site URL privately if needed.

image

Getting 404 for `script.js`

First of all, great work with the updates. Watching the conference was really inspiring.
Of course, my first thing to do was to update one of my Next.js projects and try the new goodies.

At one point I decided to try out this new Analytics feature called Audiences, but after adding it to the project I am getting these errors in the console.
Screenshot 2022-10-25 at 23 46 55

After some quick search in the vercel org I came across this repository where I found a reference for this va/script.js file.
Screenshot 2022-10-25 at 23 50 22

Overall, the audiences feature is working, I am getting visitor data in the newly enabled dashboard page; the issue only is that the browser logging this error.

If you need further details, example codes, let me know, but what i did was basically follow your guide:

  • install @vercel/analytics
  • import and place the Analytics react component into the _app.jsx file, like this:
import { Analytics } from '@vercel/analytics/react';

import '../styles/globals.css'

const MyApp = ({Component, pageProps }) => {
  return (
      <>
        <Component {...pageProps} />
        <Analytics />
      </>
  );
}

export default MyApp

HTTP 404 on `/_vercel/insights/script.js`

Firstly, thank you for offering built-in analytics support, this by itself makes it worth upgrading to Pro for me!

I followed the steps in the Audiences Quickstart Guide, including redeployment, but I'm still getting 404 on a GET for /_vercel/insights/script.js:

... and, consequently, my production dashboard shows 0 visitors:

Interestingly enough, my preview deployments don't have this issue and are actually able to track visitors, but I think it's because they are doing it through a slightly different mechanism:

I saw that #1 was confirmed as resolved by people who were experiencing it earlier, so thought I'd open a new issue.

react/jsx-runtime module not found

I'm getting the following build error.
Using React: 17.
Implemented according to guide.

Any idea on how to solve it?

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/usr/folder/project/node_modules/react/jsx-runtime' imported from /Users/usr/folder/project/node_modules/@vercel/analytics/dist/react/index.js Did you mean to import react/jsx-runtime.js?

Remove `react` from peer dependency

Currently package.json exports react as its peer dependency, which causes warning when using @vercel/analytics package from non-react projects (I'm using SvelteKit now). Per Vercel documentation, it says @vercel/analytics package is generally available from web frameworks other than react by utilizing its inject method, so having react as peer dependency is not consistent with the actual usage.

image

Bug: Internal tsconfig.json shows an error in node_modules right after fresh package install

Hi everyone! 👋

I'm in an Astro project, and after running npm install @vercel/analytics, the node_modules folder shows an error in the tsconfig.json file of this package.

The versions of a few packages that i'm using if it's helpful:

  • Node: 18.14.0
"astro": "^1.9.2",
"web-vitals": "^3.1.1",
"typescript": "^4.9.4",
"@vercel/analytics": "^0.1.8",

This is a bunch of screenshots of the error right after installing this package:

image

image

image

Feel free to ask if you have any other doubt about the error and and I'm sorry if the information is very scarce but it is one of my first opened issues! 🦄

Custom events does not work in the error boundary

Hey team, I've set up @vercel/analytics in my Next.js project, and it's working fine.

I want to track errors thrown to the error boundary in error.tsx. I've written this code:

'use client'

import { track } from '@vercel/analytics';
// ...

export default function Error({
  error,
  reset
}: {
  error: Error;
  reset: () => void;
}) {
  useEffect(() => {
    track('thrown-error', { message: error.message, time: formatDate(new Date()) });
  }, [error.message]);

  return // jsx
}

For some reason, this doesn't work as expected; there are no custom events showing up in the analytics dashboard.

When I'm in the development environment, It logs the event in the console. but in production, it does not send to the Vercel analytics dashboard.

I tried another experiment:

<button onClick={() => {
  track('test-event', { name: 'someone' });
}}>trigger</button>

This worked as expected. However, I'm unsure why the first example isn't working. Any help would be appreciated.

Must use import to load ES Module - Jest

I'm getting this error in my Jest tests when trying to us va.track:

image

Here is my jest.config.ts:

// jest.config.ts
import type { Config } from "@jest/types";
import nextJest from "next/jest";

// Sync object
const customJestConfig: Config.InitialOptions = {
  verbose: true,
  testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
  setupFiles: ["<rootDir>/.jest/setEnvVars.ts"],
  setupFilesAfterEnv: ["<rootDir>/.jest/setupTests.ts"],
  moduleDirectories: ["node_modules", "<rootDir>"],
  testEnvironment: "jest-environment-jsdom",
  transformIgnorePatterns: ["<rootDir>/node_modules/(?!isbot|swiper)"],
};

// Providing the path to your Next.js app which will enable loading next.config.js and .env files
const createJestConfig = nextJest({ dir: "./" })(customJestConfig);

module.exports = async () => {
  // Create Next.js jest configuration presets
  const jestConfig = await createJestConfig();

  // Custom `moduleNameMapper` configuration
  const moduleNameMapper = {
    ...jestConfig.moduleNameMapper,
    "swiper/react": "<rootDir>/node_modules/swiper",
    "\\.(css|less|scss|sass)$": "identity-obj-proxy",
  };

  return { ...jestConfig, moduleNameMapper, testTimeout: 20000 };
};

Any idea if this is something on my end?

How to use this module in a Nuxt 3 app?

The docs told to use inject in a main.js, but Nuxt 3 doesn't have it. I tried putting inject() or onMounted(inject) to app.vue to no avail.

The common error message is that /va/script.js doesn't exist, which is true. But then, how do I get this file? When I use this package in a Next.js 13 app, the /va/script.js is (mysteriously but conveniently) created automatically for me, but I don't know how to create it for other frameworks such as Nuxt or SvelteKit.

How should I use inject() with Nuxt 3?

Expo self hosted page and analytics

Hi guys,
I have an issue with self hosted expo project and vercel analytics.
Although I enabled the analytics on project page and included in project following

import { inject } from '@vercel/analytics';

  inject({
    debug: false,
  });

the endpoint _vercel/insights/script.js in unavailable and the statistic are missing.
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.