Tracking custom events
Learn how to send custom analytics events from your application.Custom Events are available on Pro and Enterprise plans
Vercel Web Analytics allows you to track custom events in your application using the track()
function.
This is useful for tracking user interactions, such as button clicks, form submissions, or purchases.
Make sure you have version 1.1.0 or later of
@vercel/analytics
installed.
To track an event:
- Make sure you have
@vercel/analytics
version 1.1.0 or later installed - Import
{ track }
from@vercel/analytics
- In most cases you will want to track an event when a user performs an action, such as clicking a button or submitting a form, so you should use this on the button handler
- Call
track
and pass in a string representing the event name as the first argument. You can also pass custom data as the second argument:
import { track } from '@vercel/analytics';
// Call this function when a user clicks a button or performs an action you want to track
track('Signup');
For example, if you have a button that says Sign Up, you can track an event when the user clicks the button:
import { track } from '@vercel/analytics';
function SignupButton() {
return (
<button
onClick={() => {
track('Signup');
// ... other logic
}}
>
Sign Up
</button>
);
}
You can also pass custom data along with an event. To do so, pass an object
with key-value pairs as the second argument to track()
:
track('Signup', { location: 'footer' });
track('Purchase', { productName: 'Shoes', price: 49.99 });
- The number of custom data properties you can pass is limited based on your plan
- Nested objects are not supported
- Allowed values are strings, numbers, booleans, and null
- Event name, key, and values must be no longer than 255 characters each
In scenarios such as when a user signs up or makes a purchase, it's more useful to track an event on the server-side. For this, you can use the track
function on API routes or server actions.
To set up server-side events:
- Make sure you have
@vercel/analytics
version 1.1.0 or later installed - Import
{ track }
from@vercel/analytics/server
- Use the
track
function in your API routes or server actions - Pass in a string representing the event name as the first argument to the
track
function. You can also pass custom data as the second argument
For example, if you want to track a purchase event:
'use server';
import { track } from '@vercel/analytics/server';
export async function purchase() {
await track('Item purchased', {
quantity: 1,
});
}
Was this helpful?