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/react pnpm add @faststats/react yarn add @faststats/react bun 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 { errorTracking } from "@faststats/react/error";
import { outboundLinks } from "@faststats/react/outbound-links";
import { sessionReplay } from "@faststats/react/replay";
import { webVitals } from "@faststats/react/web-vitals";
<Analytics
siteKey={process.env.NEXT_PUBLIC_FASTSTATS_SITE_KEY!}
extensions={[outboundLinks(), errorTracking(), webVitals(), sessionReplay()]}
/>;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>
);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 |
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.