How-to
5 min read

Redacting Sensitive Data from Web Analytics Events

Sometimes URLs and query parameters may contain sensitive data, such as User IDs. Learn how to redact sensitive data from your analytics events.
Table of Contents

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.

Returning null will ignore the event, while returning the event or a modified version of it will track it normally.

app/layout.tsx
'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 (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.

app/layout.tsx
'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).

app/layout.tsx
'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>
  );
}

To learn more about the beforeSend function and how it can be used with other frameworks, have a look at the @vercel/analytics package documentation.

Last updated on April 23, 2024