next-axiom
Version:
Send WebVitals from your Next.js project to Axiom.
48 lines • 1.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportWebVitalsWithPath = reportWebVitalsWithPath;
const config_1 = require("../config");
const shared_1 = require("../shared");
const url = config_1.config.getWebVitalsEndpoint();
const throttledSendMetrics = (0, shared_1.throttle)(sendMetrics, 1000);
let collectedMetrics = [];
function reportWebVitalsWithPath(metric, route) {
collectedMetrics.push({ route, ...metric });
// if Axiom env vars are not set, do nothing,
// otherwise devs will get errors on dev environments
if (!config_1.config.isEnvVarsSet()) {
return;
}
throttledSendMetrics();
}
function sendMetrics() {
const body = JSON.stringify(config_1.config.wrapWebVitalsObject(collectedMetrics));
const headers = {
'Content-Type': 'application/json',
'User-Agent': 'next-axiom/v' + config_1.Version,
};
if (config_1.config.token) {
headers['Authorization'] = `Bearer ${config_1.config.token}`;
}
const reqOptions = { body, method: 'POST', keepalive: true, headers };
function sendFallback() {
// Do not leak network errors; does not affect the running app
fetch(url, reqOptions).catch(console.error);
}
if (config_1.isBrowser && config_1.isVercelIntegration && navigator.sendBeacon) {
try {
// See https://github.com/vercel/next.js/pull/26601
// Navigator has to be bound to ensure it does not error in some browsers
// https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
navigator.sendBeacon.bind(navigator)(url, body);
}
catch (err) {
sendFallback();
}
}
else {
sendFallback();
}
collectedMetrics = [];
}
//# sourceMappingURL=webVitals.js.map