@statsy/analytics
This page is all about how to get Statsy up and running on any JS framework. We've made the steps easy to follow. If you're ready to use Statsy with JS ecosystem, you're in the right place. Let's get started!
Client-side tracking
Client-side tracking is the easiest way to get started with Statsy. It works by injecting a script into your app that sends tracking requests to Statsy. All requests are sent from the client-side, so you don't need to worry about server-side rendering.
Install @statsy/analytics
The Statsy React package is available on npm. It is recommended to install it with your package manager of choice.
pnpm i @statsy/analytics
Inject Statsy to your app
The Statsy React package provides a component that you can add to your app. It will automatically track page views and send them to Statsy.
import { inject } from "@statsy/analytics";
inject({
siteId: "YOUR_SITE_ID",
});
Track custom events
You can track custom events by using the trackEvent
function.
import { trackEvent } from "@statsy/analytics";
trackEvent({ name: "event-id" });
Read more about:
Inject props
The inject
function accepts the following props:
Prop name | Type | Description | Required |
---|---|---|---|
siteId | string | The ID of your site. You can find it in the Sites section. | Yes |
trackingEndpointDomain | string | The domain to use for tracking. Defaults to statsy.observer . | No |
eventMiddleware | func | A function that is called before sending the request. | No |
autoTrackPageviews | bool | Whether to automatically track page views. Defaults to true . | No |
Custom tracking endpoint domain
By default, the Statsy React package sends tracking requests to statsy.observer
. You can change this by using the trackingEndpointDomain
prop.
import { inject } from "@statsy/analytics";
inject({
siteId: "YOUR_SITE_ID",
trackingEndpointDomain: "statsy.example.com",
});
Learn more about custom domains in the Tracking Script section.
Customizing events with eventMiddleware
The eventMiddleware
function is called before sending the request to Statsy. It receives the following arguments:
Argument name | Type | Description |
---|---|---|
event | object | The event object that will be sent to Statsy. |
event.name | string | The name of the event. |
event.href | string | The href of the event. |
The eventMiddleware
option lets you change details about an event before sending it to Statsy. For example, you can set it up so that any event with "/admin" in the URL is ignored.
When you make it return null
, no event details are sent. Plus, you can tweak the URL however you want, like getting rid of parts after the question mark.
import { inject } from "@statsy/analytics";
inject({
siteId: "YOUR_SITE_ID",
trackingEndpointDomain: "statsy.example.com",
eventMiddleware={(event) => {
// Ignore all events that have a `/admin` inside the URL
if (event.href.includes("/admin")) {
return null;
}
// Remove the `token` query parameter from the URL
if (event.href.includes("token")) {
let url = new URL(event.href);
url.searchParams.delete("token");
return {
...event,
href: url.toString(),
};
}
return event;
}}
});
Server-side tracking
You can use the @statsy/analytics package on the server-side as well. This is useful if you're using a server-side rendering framework like Next.js.
Use cases for server-side tracking:
- Get more accurate pageviews tracking, server-side tracking can't be blocked by ad blockers.
- Track custom events that happen on the server-side.
Server-side tracking can be run on any Node.js/Deno server and Edge runtime (like Vercel or Netlify Edge Functions).
Server-side tracking tracks pageviews and custom events. If you want to track Web Vitals and Carbon Footprint you still need to use the client-side tracking script.
You can combine both approaches to get the best of both worlds. For example, you can use the server-side tracking to track pageviews and the client-side tracking to track Web Vitals and Carbon Footprint. Remember to disable auto pageviews tracking in the client-side tracking script.
import { inject } from "@statsy/analytics";
inject({
siteId: "YOUR_SITE_ID",
autoTrackPageviews: false,
});
Set up the Statsy API Key
First, you need to create a token key for your account in Statsy. Go to the Personal Account settings and create a new token key.
Then add it to your app as an environment variable.
STATSY_API_KEY=YOUR_API_KEY
API key is used to authenticate your requests. It is recommended to use environment variables to store it.
It should not be exposed in your code or sent to the client since everyone with the API key can send data to your account. This can lead to incorrect analytics data.
Track pageviews in your app
The Statsy React package provides a component that you can add to your app. It will automatically track page views and send them to Statsy.
In Next.js, you can use the middleware
function to track pageviews. It will automatically track all requests with the Content-Type: text/html
header.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { trackPageview } from "@statsy/analytics";
export async function middleware(request: NextRequest) {
await trackPageview({ request });
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};
Track custom events
You can track custom events by using the trackEvent
function.
import { NextRequest, NextResponse } from "next/server";
import { trackEvent } from "@statsy/analytics";
export async function POST(request: NextRequest) {
// send data to your API
const res = await fetch("https://api.example.com/submit-form", {
method: "POST",
body: request.body,
});
if (res.ok) {
// track the event
await trackEvent({
name: "form-submitted",
props: {
formId: "contact-form",
formName: "Contact Form",
},
request,
});
}
return NextResponse.json(data);
}