Metrics responsed in random order on querying CrUX Report API

83 Views Asked by At

I queries to CrUX Report API, as dev docs show.

Instead of origin I use url to get data for certain URLs, so my query looks like:

curl https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=API_KEY \
  --header 'Content-Type: application/json'   --data '{"url":"https://www.spiegel.de/schlagzeilen/"}'

I do this one by one for different urls.

My problem: responses are coming in different order: for the first query CLS comes as first metric, for the second query - FID and so on.

This issue doesn't depend on the kind I run queries: cURL in terminal, by Postman, or by Google App script in Google Sheets.

I tried to setup an explicit metrics order in the request, like

curl https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=API_KEY \
      --header 'Content-Type: application/json'   --data '{"url":"https://www.spiegel.de/schlagzeilen/","metrics":["cumulative_layout_shift","first_contentful_paint","first_input_delay","largest_contentful_paint"]}'

but responses come still in random order.

Q: is there a possibility to force a metrics order in the response I wish to have?

1

There are 1 best solutions below

2
Rick Viscomi On

While the metrics input parameter does allow you to list the metrics that get output in the results, it doesn't control the ordering of the metrics. There is no other input mechanism to enforce a particular metric ordering.

That said, the metrics response is a JSON object, which is an inherently unordered data structure. The ordering of the object keys may affect how the object is iterated, for example Object.fromEntries(response.record.metrics) will iterate over the metrics in the order they appear.

If the order is critical to your application, I would recommend deterministically looping through a constant array of metric IDs rather than iterating over the object keys. For example:

const METRICS = ['first_contentful_paint', 'largest_contentful_paint', 'first_input_delay', 'cumulative_layout_shift'];
const cruxData = METRICS.map(metric => response.record[metric]);

I see you're using cURL to issue the requests, so you can adapt this strategy to whichever programming language you use to parse the results.