React and Next.js
Add FastStats Web Analytics to a React or Next.js app
The @faststats/react package wraps the browser SDK in a single component and a
set of hooks. It works with any React app and with the Next.js App Router.
Install
npm install @faststats/reactpnpm add @faststats/reactyarn add @faststats/reactbun add @faststats/reactAdd the Analytics Component
Render the Analytics component once, near the root of your app. It starts
tracking when it mounts and cleans up when it unmounts. You never have to create
an instance by hand.
import { Analytics } from "@faststats/react";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Analytics siteKey={process.env.NEXT_PUBLIC_FASTSTATS_SITE_KEY!} />
{children}
</body>
</html>
);
}import { Analytics } from "@faststats/react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Analytics siteKey={import.meta.env.VITE_FASTSTATS_SITE_KEY} />
<App />
</StrictMode>,
);The component accepts every option from the SDK. Here is a fuller example that turns on a few extra features.
import { Analytics } from "@faststats/react";
import { errorTracking } from "@faststats/react/error";
import { sessionReplay } from "@faststats/react/replay";
import { webVitals } from "@faststats/react/web-vitals";
<Analytics
siteKey={process.env.NEXT_PUBLIC_FASTSTATS_SITE_KEY!}
extensions={[errorTracking(), webVitals(), sessionReplay()]}
/>;Options are read when the component mounts. Only changes to the consent prop
are applied to the running client afterwards. See
Configuration for the full list.
Track Custom Events
Use the hooks inside client components. They access the instance owned by the
nearest mounted Analytics component.
"use client";
import { useTrack } from "@faststats/react";
export function BuyButton() {
const track = useTrack();
return (
<button
type="button"
onClick={() => track("purchase", { plan: "pro", price: 29 })}
>
Buy now
</button>
);
}useEvent builds a stable handler when the name and properties do not change.
const onSignup = useEvent("signup", { source: "hero" });
return (
<button type="button" onClick={onSignup}>
Sign up
</button>
);Identify Users and Update Traits
useIdentify links the visitor to your user after sign-in. useSetTraits
updates traits on that user later without a full identify, for example after a
plan upgrade.
"use client";
import { useSetTraits } from "@faststats/react";
export function UpgradeButton() {
const setTraits = useSetTraits();
return (
<button
type="button"
onClick={async () => {
await upgradeToPro();
await setTraits({ plan: "pro" });
}}
>
Upgrade
</button>
);
}Pass { mode: "setOnce" } to only set traits the user does not have yet, such
as where they first came from. Called before useIdentify, traits are kept in
memory for the current page and sent right after the next identify on that
page.
useSetTraits needs @faststats/react 0.14.0 or later. See
Identify for details.
Available Hooks
| Hook | Returns |
|---|---|
useAnalytics | The active WebAnalytics instance or null |
useTrack | A function that sends custom events |
useEvent | A memoized handler for one named event |
useIdentify | The identify function |
useSetTraits | The setTraits function |
useLogout | The logout function |
useConsentMode | The setConsentMode function |
useOptIn | A shortcut that grants consent |
useOptOut | A shortcut that denies consent |
Read more in Events, Identify, and Consent and Cookieless.
Server Side Routes
The React package only runs in the browser. If you also want to capture errors thrown in Next.js route handlers or server functions, read the server section in Error Tracking.