Coder Social home page Coder Social logo

googlechromelabs / web-vitals-report Goto Github PK

View Code? Open in Web Editor NEW
500.0 18.0 48.0 3.9 MB

Measure and report on your Web Vitals data in Google Analytics

Home Page: https://web-vitals-report.web.app

License: Apache License 2.0

JavaScript 71.09% HTML 9.50% CSS 19.40%

web-vitals-report's Introduction

⚡ Web Vitals Report

The Web Vitals Report is a web app that makes it easy for users of the web-vitals JavaScript library to create custom visualizations of the data they've sent to Google Analytics. The app is available to use as a standalone tool, or you can fork it and customize it to your needs.


web-vitals-report

Overview

Google Analytics does not currently provide out-of-the-box support for Web Vitals, but it does offer a number of options for measuring custom events, which you can then aggregate and report on manually.

If you're a current Google Analytics user, there are a lot of advantages to capturing your site's Web Vitals data in the tool you're already using. Primarily, it allows you to compare performance and page experience across your existing user segments—to see how it affects your goals, conversions, and other business metrics.

This is critical, as it can help you answer questions like:

  • How do my site's Web Vitals correlate with its bounce rate?
  • Do pages perform better for returning users than new users?
  • Are users more likely to make a purchase when the experience is better?

The Web Vitals Report can give you insight into all of these questions, and more!

How to use the app

Step 0: (prerequisites)

The most important step—which must be done before you can use the Web Vitals Report—is to add the web-vitals JavaScript library to your site and configure it to send data to Google Analytics

If you have not completed this step, you'll get an error when trying to create any reports.

Step 1: (authorize)

Navigate to web-vitals-report.web.app and click the "Sign in with Google" button. The sign-in flow will prompt you for permission to allow the app to view your Google Analytics data, which is needed in order to create the report.

Step 2: (configure)

After you've logged in, a form will appear asking you to select:

  1. Your Google Analytics account (and property and view)
  2. A date range to query
  3. Select the segments to compare results for

While the app does suggest a few interesting segments to compare, you're not limited to just these suggestions. If you select the bottom option "Choose segments", you'll be able to pick any segment you want.

If a particular segment you're interested in looking at is not in the list, you can always create it yourself.

Advanced configuration options

There is also an option to "use advanced options (configurable per account)". These options are useful if you've customized your web-vitals JS implementation (e.g. changed the recommended event action or label values or the metric names). They also allow you to further filter the report (e.g. only events matching a particular custom dimension value).

Debug dimension

Within the advance configuration options section is a field labelled "Debug dimension". This option can be used as an additional drill-down dimension to help identify and debug Web Vitals issues.

You can set any valid dimension here, but typically this will be a custom dimension in the form of ga:dimensionXX (were XX refers to the index of the dimension shown in the Google Analytics Admin admin section under Property Settings > Custom Definitions > Custom Dimensions).

For details on what types of debug information is useful to capture, see: Debug Web Vitals in the field

Filter reference

The syntax for specifying filters is based on the format used in the Core Reporting API, with a few limitations:

  • Only dimension filters are supported (no metric filters)
  • Only AND combinations can be used (no OR combinations)

For example, the following filter would limit the report to only include Web Vitals events on "article" pages:

ga:pagePath=~^/articles/

And this example would limit it to just non-U.S. visitors who landed on a "product" page:

ga:country!=United States;ga:landingPagePath=~^/product/\d+

Step 3: (create & analyze)

Once you've configured the report, click "Submit" to make the API request(s) and render the report.

NOTE: querying your data and generating the report can sometimes take a long time, especially if your site receives a lot of traffic (>100K visitors a day). Refer to the limitations section for details.

The generated report consists of a histogram and timeline for each of the Core Web Vitals metric, helping you visualize how the results differ by segment. It also includes a drill down of the top five countries and pages (by total number of Web Vitals events received), so you can see if certain pages or user populations perform better or worse than others.

All of the scores reported represent the value at the 75th percentile for all metric events in that segment and dimension group. To help you quickly assess your overall compliance with the Core Web Vitals thresholds, each score is colored based on the following buckets (following the thresholds outlined in web.dev/vitals:

  • Green: "good"
  • Yellow: "needs improvement"
  • Red: "poor"

Limitations

While the Web Vitals Report app is powerful, it does have some limitations. In particular, large sites may find it quite slow or run up against row limitations (see below).

In general, this tool is best suited for small to mid-size websites—particularly those who are not large enough to have all their pages appear in the Chrome User Experience Report (CrUX) dataset.

Sites that send fewer than 100,000 Web Vitals events per day should not have any problems using this report. For larger sites, on-demand reporting of unaggregated event data is likely not practical.

1 million row limit

Google Analytics imposes a limit of 1 million unique rows in each report. After 1 million rows all results are grouped into an "(other)" bucket.

Unfortunately, in order for Web Vitals Report to build a distribution and calculate the 75th percentile, it needs access to each individual event value. As a result, a report cannot be created if a site has received more than 1 million Web Vitals events per day.

Large sites still wishing to use this tool may want to consider sampling the number of events they send to Google Analytics (e.g. only send events for 10% of users). Another option is to use the BigQuery export feature in Google Analytics, which does not have the 1 million row limit restriction. However, BigQuery export is beyond the scope of the Web Vitals Report tool.

Google Analytics 4 (GA4) properties are not supported

At the moment, the Web Vitals Report only supports Universal Analytics properties. Google Analytics 4 (GA4) is not supported as it's APIs are still in alpha preview and some required features are missing.

Once the APIs are publicly available and all required features have been added, GA4 properties will be supported.

Build and run the app locally

Developers can use the Web Vitals Report app at web-vitals-report.web.app as much as they want, but they can also fork the repo and build their own version of the tool—customizing it to meet their specific needs.

To build and run the app locally, follow these steps:

  1. Clone the repo (or a fork) to your local machine.
  2. Run npm install to download and install all dependencies.

Before you can run the app locally, you'll need to create your own OAuth 2.0 credential in order to query the Google Analytics APIs.

  1. Create a new project in the Google Cloud Console and enable the following APIs: i. Google Analytics API ii. Analytics Reporting API
  2. Set up OAuth 2.0 in your new project and create a client ID and make sure to add localhost:4040 to the list of Authorized JavaScript origins.
  3. In your clone of the web-vitals-report repo, replace the client IDs in the oauth.config.json file with the client ID you just created. (The file contains separate client IDs for dev and prod builds, but it's OK to use the same client ID for both, as long as all authorized domains are correctly configured).

Once you have your own client ID, you can run the app locally:

  1. Run npm start to build the app and start a local development server
  2. Visit localhost:4040 to use the app.

License

Apache 2.0

web-vitals-report's People

Contributors

dependabot[bot] avatar philipwalton avatar tunetheweb 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

web-vitals-report's Issues

How can i get web vital report with each page?

I added web vital npm at our page to get Web Vitals report.
and this is what i added to my code (send to google analytics to analyze with web vital report)

function sendToGoogleAnalytics({ name, delta, id }: { name: any; delta: any; id: any }) {
  // Assumes the global `ga()` function exists, see:
  // https://developers.google.com/analytics/devguides/collection/analyticsjs

  ReactGA.ga('send', 'event', {
    eventCategory: 'Web Vitals',
    eventAction: name,
    // The `id` value will be unique to the current page load. When sending
    // multiple values from the same page (e.g. for CLS), Google Analytics can
    // compute a total by grouping on this ID (note: requires `eventLabel` to
    // be a dimension in your report).
    eventLabel: id,
    // Google Analytics metrics must be integers, so the value is rounded.
    // For CLS the value is first multiplied by 1000 for greater precision
    // (note: increase the multiplier for greater precision if needed).
    eventValue: Math.round(name === 'CLS' ? delta * 1000 : delta),
    // Use a non-interaction event to avoid affecting bounce rate.
    nonInteraction: true,
    // Use `sendBeacon()` if the browser supports it.
    transport: 'beacon'

    // OPTIONAL: any additional params or debug info here.
    // See: https://web.dev/debug-web-vitals-in-the-field/
    // dimension1: '...',
    // dimension2: '...',
    // ...
  })
}

But as you can see in below i can't get web vital report with each pages with only total web vital score . So. how can i get web vitals with each page?

스크린샷 2021-05-28 오후 1 30 50

INP metrics

Hello,

I want to monitor the new INP metric using your code, what do I need to add to the following code to make it work.

`<script type="module">
import {onCLS, onFID, onLCP} from 'https://unpkg.com/web-vitals@3/dist/web-vitals.attribution.js?module';
function sendToGoogleAnalytics({name, delta, id, attribution}) {
let debug_target;

switch (name) {
case 'CLS':
debug_target = attribution.largestShiftTarget;
break;
case 'FID':
debug_target = attribution.eventTarget;
break;
case 'LCP':
debug_target = attribution.element;
break;
}

gtag('event', name, {
event_category: 'Web Vitals',
event_label: id,
value: Math.round(name === 'CLS' ? delta * 1000 : delta),
non_interaction: true,
dimension2: debug_target });
}

onCLS(sendToGoogleAnalytics);
onFID(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);
</script>`

Thanks in advance!

CLS graph shows excessively high count of 0 values

Scores for p75 for CLS seem to be computed correctly, but display a graph with an extremely large number of 0 values. Are null values showing up on the graph as 0 but properly discarded in the average computation?

The following image shows mobile traffic CLS which the dashboard scores reasonably as 0.135 despite the graph showing almost entirely 0 values that would imply an average way lower, possibly 0.02.
image

Other graphs show distributions concordant with their averages and without an excess of 0 values.

Provide examples to collect Web Vitals from AMP enabled Websites using GA and GTM

I use Google Tag Manager for AMP enabled wordpress site. And it currently has a generic page view tracking thanks to Google Site Kit Plugin.

I can't place web-vitals script from GTM anymore as it is not supported in AMP container. But I recently found out that you can use amp-analytics with built in variables like this.

<amp-analytics type="googleanalytics">
	<script type="application/json">
        {
          "vars": {
            "gtag_id": "UA-XXXXXXXXX-X",
            "config": {
              "UA-XXXXXXXXX-X": {
                "groups": "default"
              }
            }
          },
          "triggers": {
            "default pageview": {
              "on": "visible",
              "request": "pageview",
              "vars": {
                "title": "{{title}}"
              },
              "extraUrlParams": {
                "lcp": "${largestContentfulPaint}",
                "cls": "${cumulativeLayoutShift}",
                "fid": "${firstInputDelay}"
              }
            }
          }
        }	
	</script>
</amp-analytics>

But honestly, I have no idea how this value gets mapped on the google analytics. Also, I don't have enough knowledge to fit the same setting in Google Tag manager.

So If you could add instructions for AMP enabled websites as well it would be a great addition to the documentation.

The AMP enabled websites are only 0.1% of total websites in the web. But people like me switched to AMP mainly for Core-Web-Vitals benefit. So If you could provide a consistent way to test the results, It would be helpful.

Field Data problem with GA

Hi Barry!

We are using your code on our Shopify store to measure field data Core Web Vitals through the Web Vitals Report app. It's a must have!

When we place the Analytics code after the web vitals library, it doesn't sends the data to GA.

When we place the Analytics code before the web vitals library, it works and sends the data to our GA.

The problem is, in Shopify, the GA code is buried in with other tracking scripts like this:

trekkie.load(
      {"Trekkie":{"appName":"storefront","development":false,"defaultAttributes":{"shopId":9903636546,"isMerchantRequest":null,"themeId":136834416853,"themeCityHash":"11864794253938457520","contentLanguage":"en","currency":"USD"},"isServerSideCookieWritingEnabled":true,"monorailRegion":"shop_domain"},"Google Analytics":{"trackingId":"UA-146128799-1","domain":"auto","siteSpeedSampleRate":"10","enhancedEcommerce":true,"doubleClick":true,"includeSearch":true},"Facebook Pixel":{"pixelIds":["678075513264158"],"agent":"plshopify1.2"},"Pinterest Pixel":{"pixelId":"2612622350597"},"Google Gtag Pixel":{"conversionId":"G-KQKGHFJ06K","eventLabels":[{"type":"search","action_label":["G-KQKGHFJ06K","AW-708062442\/lKkdCO2DvKsBEOrZ0NEC"]},{"type":"begin_checkout","action_label":["G-KQKGHFJ06K","AW-708062442\/y3NFCOqDvKsBEOrZ0NEC"]},{"type":"view_item","action_label":["G-KQKGHFJ06K","AW-708062442\/OtSXCOSDvKsBEOrZ0NEC","MC-1FB355FTP1"]},{"type":"purchase","action_label":["G-KQKGHFJ06K","AW-708062442\/yhhZCPLMuI8YEOrZ0NEC","MC-1FB355FTP1"]},{"type":"page_view","action_label":["G-KQKGHFJ06K","AW-708062442\/yyTGCN6DvKsBEOrZ0NEC","MC-1FB355FTP1"]},{"type":"add_payment_info","action_label":["G-KQKGHFJ06K","AW-708062442\/0B6MCPCDvKsBEOrZ0NEC"]},{"type":"add_to_cart","action_label":["G-KQKGHFJ06K","AW-708062442\/uHNtCOeDvKsBEOrZ0NEC"]}],"targetCountry":"US"},"Session Attribution":{},"S2S":{"facebookCapiEnabled":true,"facebookAppPixelId":"678075513264158","source":"trekkie-storefront-renderer"}}
    );

Since it's very hard to extract only the Google Analytics code from the above and place it before (above) the web vitals library code.

What I do is leave the above GA code as it is (since I'm afraid to mess with the mess) and on top of it, add GA code from Google Analytics:

image

Now we have two GA code with the same Tracking ID as you can tell from the source code of the website: https://www.stunningcanvasprints.com/

and it works because now, we do get the field data in our analytics except here's 1 strange issue:

image

Although, our Analytics collects all sort of data perfectly fine plus we now collect the Field Data too but, the Bounce Rate drops.

This happens on every Shopify store when we place the clean GA code before the web vitals library.

This does not happens on WordPress.

Please advise, how can we use your code on Shopify store without affecting Bounce Rate tracking?

TIA

names of the scores are case sensitive

First of all thanks for building the app. It adds a ton of value to our teams who can now better understand the scores.
When setting up the report in advanced section I noticed that the names of the scores have to match the exact casing as you have it in GA. In our case, we lowercase all incoming data to avoid inconsistencies in the reports. Therefore the default setting of the app didn't work for us.

I think it would be helpful to update the app so it would match the score names regardless of the casing.

Sorry if my comment is not very precise, I'm happy to elaborate if any more details are needed.

GA4 Support

I looked into this briefly and figured we should have a tracking issue.. At the very least to point to relevant resources.

As mentioned in the site and readme…

At the moment, the Web Vitals Report only supports Universal Analytics properties. Google Analytics 4 (GA4) is not supported as it's APIs are still in alpha preview and some required features are missing.

I poked at the new Data API, which has a newish 'beta' release (as of July '22). And I'm starting to see hints that it may work here too. (I completely defer to you Phil on what's actually real) :)

I did get https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/batchRunReports running with a GA4 property of mine. (Though sadly I don't have a wv.js + GA4 combo myself…)

I'm seeing support for Custom Dimensions and metrics.. and it appears to connect with the custom "event"s that are used w/wv.js in GA4?

If that's true, then perhaps we have all the ingredients we need?


Separately, in a previous conversion, @philipwalton mentioned there's a Bigtable Export for GA4. https://support.google.com/firebase/answer/7029846?hl=en & https://measuremindsgroup.com/bigquery-with-google-analytics-4 That, at least, could be feasible if a backend is in-scope. ;)

The app is not updating values for the current day

The Web Vitals Report site uses IndexedDB to cache API results, so it doesn't have to re-request them multiple times for the same date/configuration combination.

In most cases (using the default options) this works fine, but if you update the date range to include the current date, it's possible that the cached data will not represent the full set of data for that day. The reason is because the app will not re-request data for a date it already has cached.

Google launched new core web vital metric?

Hi @tunetheweb and @philipwalton thank you for your huge contribution to accelerating the web performance and making our world eco-friendly. I'm grateful to you!

Since Google has launched INP, is the following code correct since I'm not getting any INP values in your Web Vitals Report app:

image

<script type="module">
import {onCLS, onFID, onLCP, onINP} from 'https://unpkg.com/web-vitals@3/dist/web-vitals.attribution.js?module';

function sendToGoogleAnalytics({name, delta, id, attribution}) {
  let debug_target;

  switch (name) {
    case 'CLS':
      debug_target = attribution.largestShiftTarget;
      break;
    case 'FID':
      debug_target = attribution.eventTarget;
      break;
    case 'LCP':
      debug_target = attribution.element;
      break;
    case 'INP': // assuming the name of the new metric is 'INP'
      debug_target = attribution.inpTarget; // assuming 'inpTarget' is the attribute for the new metric
      break;
  }

  gtag('event', name, {
    event_category: 'Web Vitals',
    event_label: id,
    value: Math.round(name === 'CLS' ? delta * 1000 : delta),
    non_interaction: true,
    dimension2: debug_target
  });
}

onCLS(sendToGoogleAnalytics);
onFID(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);
onINP(sendToGoogleAnalytics); // Again, assuming the new metric's function is 'onINP'
</script>

'Pages' section of Report capped at 5?

Hello! Love the app but would really benefit from being able to specify how many pages I want to see in the report. The documentation says:

It also includes a drill down of the top five countries and pages (by total number of Web Vitals events received), so you can see if certain pages or user populations perform better or worse than others.

I know for a fact we're sending web vitals info from thousands of pages, so not sure why I can only see five? Also curious as to how it choses said pages. Is it based off performance? They seem to be a mix of good and bad performing pages.

Anyhow, any help would be much appreciated, thank you!

Field Data not gathering despite a lot of traffic

I'm using the exact same code in 2 websites:

<script type="module">
import {onCLS, onFID, onLCP} from 'https://unpkg.com/web-vitals@3/dist/web-vitals.attribution.js?module';
function sendToGoogleAnalytics({name, delta, id, attribution}) {
 let debug_target;

  switch (name) {
    case 'CLS':
     debug_target = attribution.largestShiftTarget;
      break;
    case 'FID':
     debug_target = attribution.eventTarget;
      break;
    case 'LCP':
     debug_target = attribution.element;
      break;
  }
  
  gtag('event', name, {
    event_category: 'Web Vitals',
    event_label: id,
    value: Math.round(name === 'CLS' ? delta * 1000 : delta),
    non_interaction: true,
	dimension2: debug_target  });
}

onCLS(sendToGoogleAnalytics);
onFID(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);
</script>
  1. https://www.mycannabis.com
  2. https://trainingcoursematerial.com

The first website (mycannabis) is getting only 500 users per day out of which 40% are Chrome users

image

image

The second website (trainingcourse) is getting 800+ users per day out of which 60% are Chrome users

image

image

Both of the websites are collecting web vitals data when I check in Network Tab:

image

The first website, despite getting less traffic, less % of Chrome users, less % of Andriod users, gets A LOT of data collected in Web Vitals Report app:

image

Yet, the second website with more traffic, more % of Chrome and Andriod users, gets little to non-existent data collected when compared to the same date period:

image

Both of the UA analytics property are functioning and not retired yet.

Transferring field attribution to UA

First of all, I want to thank you for an incredibly cool tool!

We are trying to deal with the transfer of attribution of fields to the UA from Google.

Step by step:

  1. We have connected the library and added a function:
import {onCLS, onFID, onLCP} from 'https://unpkg.com/web-vitals@3/dist/web-vitals.attribution.js?module';
function sendToGoogleAnalytics({name, delta, value, id, attribution}) {...}

  1. and enabled field attribution:
  switch (name) {
    case 'CLS':
      eventParams.debug_target = attribution.largestShiftTarget;
      break;
    case 'FID':
      eventParams.debug_target = attribution.eventTarget;
      break;
    case 'LCP':
      eventParams.debug_target = attribution.element;
      break;
  }
    case 'FID':
      eventParams.debug_target = attribution.eventTarget;
      break;
    case 'LCP':
      eventParams.debug_target = attribution.element;
      break;
  }
  1. Passing the results to GA
onCLS(sendToGoogleAnalytics);
onFID(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);

But we do not get the result in the form of fields (div and so on) that led to the greatest changes in CLS, FND, LCP.

Tell me, please, what else do we need to do?

[Question] Recommendation for A/B testing a particular JavaScript snippet with Web Vitals Report?

Hello,

We are looking to implement Core Web Vitals first on our site, then eventually on our clients' websites. Particularly, we want to measure the web vitals both with and without a particular JavaScript snippet running on the page, and be able to easily compare/contrast these values to understand the UX impact of the snippet.

We can implement a "coin flip" mechanic that determines whether or not to inject the JavaScript, and report on the Core Web Vitals in every case.

It seems like we might somehow be able to take advantage of eventLabel and grouping (or maybe some other GA event property), but are unsure how we can configure web-vitals-report correctly for this particular use-case.

Are there any recommendations on how to approach this problem? Any help would be greatly appreciated.

Add support for TTFB and FCP

Since TTFB and FCP are also metrics from web core vitals api, is it possible to be added to the report?

Thank you

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.