Redacting Sensitive Data from Web Analytics Events
Learn how to redact sensitive data from your Web Analytics events.Sometimes, URLs and query parameters may contain sensitive data. This could be a user ID, a token, an order ID, or any other data that you don't want to be sent to Vercel. In this case, you may not want them to be tracked automatically.
To prevent sensitive data from being sent to Vercel, you can pass in the beforeSend
function that modifies the event before it is sent. To learn more about the beforeSend
function and how it can be used with other frameworks, see the @vercel/analytics package documentation.
To ignore an event or route, you can return null
from the beforeSend
function. Returning the event or a modified version of it will track it normally.
import { Analytics, type BeforeSendEvent } from '@vercel/analytics/next';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<title>Next.js</title>
</head>
<body>
{children}
<Analytics
beforeSend={(event: BeforeSendEvent) => {
if (event.url.includes('/private')) {
return null;
}
return event;
}}
/>
</body>
</html>
);
}
To apply changes to the event, you can parse the URL and adjust it to your needs before you return the modified event.
In this example the query parameter secret
is removed on all events.
'use client';
import { Analytics } from '@vercel/analytics/react';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<title>Next.js</title>
</head>
<body>
{children}
<Analytics
beforeSend={(event) => {
const url = new URL(event.url);
url.searchParams.delete('secret');
return {
...event,
url: url.toString(),
};
}}
/>
</body>
</html>
);
}
You can also use beforeSend
to allow users to opt-out of all tracking by setting a localStorage
value (for example va-disable
).
'use client';
import { Analytics } from '@vercel/analytics/react';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<title>Next.js</title>
</head>
<body>
{children}
<Analytics
beforeSend={(event) => {
if (localStorage.getItem('va-disable')) {
return null;
}
return event;
}}
/>
</body>
</html>
);
}
Was this helpful?