Skip to main content

Event Schema

An event schema helps you define your custom events in a type-safe way.

This ensures:

✅ You don’t mistype event names
✅ You get autocomplete in your IDE
✅ You can easily see what events exist in the app

By using an event schema, you centralize all your analytics events in one place. This makes it easier to maintain, refactor, and onboard new developers. You can quickly audit which events are tracked and update them as your application evolves.


Defining an event schema

import { defineEventSchema, createUseTrack } from "react-matomo-kit";

export const eventSchema = defineEventSchema({
user: {
select: { category: "User", action: "Select" },
},
cat: {
click: { category: "Cat", action: "Click", name: "", value: 0 },
submit: { category: "Cat", action: "Submit" },
},
});

export const useTrack = createUseTrack(eventSchema);

Here, defineEventSchema takes an object describing all your events, grouped by logical categories (like user or cat). Each event specifies the required Matomo fields (category, action, and optionally name and value). This schema is then used to generate a custom hook with createUseTrack, ensuring only valid events can be tracked.


Using the schema

const { track } = useTrack();

track("cat.click", {
name: "Clicked Cat",
value: 1,
});

track("user.select", {
name: "Alice",
});

When you use the track function, your IDE will suggest valid event keys and required properties. If you try to track an event not defined in the schema, TypeScript will show an error. This prevents mistakes and makes your analytics code safer and easier to maintain.


How it works

  • defineEventSchema() builds a strongly typed object.
  • createUseTrack() generates a hook that only accepts valid event keys.
  • This gives full type checking and autocomplete.
  • If you add or remove events from the schema, your codebase will immediately reflect those changes, reducing the risk of tracking invalid or outdated events.
  • The schema-driven approach also makes it easier to document and share your analytics implementation with your team.