mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-08 04:22:09 +00:00
[examples] Add Vercel Analytics for CRA/SvelteKit templates. (#7894)
Successfully tested with: - [CRA](https://front-git-analytics-for-all-frameworks.vercel.sh/now-examples/create-react-app/analytics?device=desktop&timePeriod=1d&percentile=75&timeInterval=3h&sort=datapoints&search=) - [SvelteKit](https://front-git-analytics-for-all-frameworks.vercel.sh/now-examples/sveltekit/analytics?device=desktop&timePeriod=1d&percentile=75&timeInterval=3h&sort=datapoints&search=) Dependencies have also been updated 👍
This commit is contained in:
@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import { sendToVercelAnalytics } from './vitals';
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
@@ -11,7 +12,4 @@ ReactDOM.render(
|
||||
document.getElementById('root')
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
||||
reportWebVitals(sendToVercelAnalytics);
|
||||
|
||||
41
examples/create-react-app/src/vitals.js
Normal file
41
examples/create-react-app/src/vitals.js
Normal file
@@ -0,0 +1,41 @@
|
||||
const vitalsUrl = 'https://vitals.vercel-analytics.com/v1/vitals';
|
||||
|
||||
function getConnectionSpeed() {
|
||||
return 'connection' in navigator &&
|
||||
navigator['connection'] &&
|
||||
'effectiveType' in navigator['connection']
|
||||
? navigator['connection']['effectiveType']
|
||||
: '';
|
||||
}
|
||||
|
||||
export function sendToVercelAnalytics(metric) {
|
||||
const analyticsId = process.env.REACT_APP_VERCEL_ANALYTICS_ID;
|
||||
if (!analyticsId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const body = {
|
||||
dsn: analyticsId,
|
||||
id: metric.id,
|
||||
page: window.location.pathname,
|
||||
href: window.location.href,
|
||||
event_name: metric.name,
|
||||
value: metric.value.toString(),
|
||||
speed: getConnectionSpeed(),
|
||||
};
|
||||
|
||||
console.log({ body });
|
||||
const blob = new Blob([new URLSearchParams(body).toString()], {
|
||||
// This content type is necessary for `sendBeacon`
|
||||
type: 'application/x-www-form-urlencoded',
|
||||
});
|
||||
if (navigator.sendBeacon) {
|
||||
navigator.sendBeacon(vitalsUrl, blob);
|
||||
} else
|
||||
fetch(vitalsUrl, {
|
||||
body: blob,
|
||||
method: 'POST',
|
||||
credentials: 'omit',
|
||||
keepalive: true,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user