Synthèse automatique
Ajoute des événements d’analytique produit (Snowplow) pour suivre les interactions utilisateur dans le frontend de Metabase.
Points forts
- Impose une validation TypeScript au site d’appel via trackSimpleEvent et SimpleEventSchema.
- Fournit une checklist et une convention de fichiers claire, avec les fonctions de tracking dans le analytics.ts de la fonctionnalité.
- Décourage l’ajout de nouveaux schémas personnalisés et oriente vers l’événement simple standard.
- Rappelle la convention de nommage snake_case au passé et l’emplacement des types locaux.
Limites
- Très spécifique au frontend Metabase et à Snowplow ; ne couvre pas la configuration de collecte ni l’exploitation des données.
- Ne fournit pas de taxonomie complète ni de liste des événements existants.
- La partie sur les schémas personnalisés est volontairement limitée, car ils sont legacy.
À utiliser lorsqu’il faut instrumenter une nouvelle interaction utilisateur dans le code frontend de Metabase.
À ne pas utiliser pour un autre framework, un autre outil d’analytique, ou pour concevoir l’ensemble d’un plan de mesure produit.
Analyse de sécurité
SûrThe skill is pure documentation/guidance for adding Snowplow analytics events to a TypeScript frontend. Its allowed tools are limited to Read, Write, Edit, Grep, and Glob — no bash, network, docker, or credential access. There are no destructive commands, no exfiltration of secrets, no obfuscated payloads, and no attempts to disable safety controls. All code samples are ordinary React/TypeScript snippets that call a local tracking helper.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Add a Snowplow analytics event for when a user applies filters in the Metabase data studio table picker. Create the tracking function in the feature's analytics.ts and call it from the component.Create a simple past-tense snake_case analytics event for opening a dashboard and wire it into the Metabase frontend interaction point using trackSimpleEvent.Check this Metabase frontend change for analytics events: ensure it uses trackSimpleEvent, keeps any local field unions in analytics.ts, and does not add event types to metabase-types/analytics/event.ts.name: analytics-events description: Add product analytics events to track user interactions in the Metabase frontend allowed-tools: Read, Write, Edit, Grep, Glob
Frontend Analytics Events Skill
This skill helps you add product analytics (Snowplow) events to track user interactions in the Metabase frontend codebase.
Quick Reference
Analytics events in Metabase use Snowplow with typed event schemas. Simple events are declared where they are used — trackSimpleEvent is generic and validates the payload at the call site.
Key Files:
frontend/src/metabase/analytics/event.ts- Core tracking functions,trackSimpleEvent/trackSchemaEvent(import frommetabase/analytics)frontend/src/metabase-types/analytics/event.ts- The sharedSimpleEventSchemaonly. Do not add event types here (see below)frontend/src/metabase-types/analytics/schema.ts- Schema registry (custom/legacy schemas only)- Feature-specific
analytics.tsfiles - Where your tracking functions and any local types live
Quick Checklist
When adding a new analytics event:
- [ ] Pick an event name (snake_case, past tense)
- [ ] Add a tracking function to the feature's
analytics.tsfile, callingtrackSimpleEvent() - [ ] Keep any field unions (e.g.
"success" | "failure") as local types in that same file - [ ] Import and call the tracking function at the interaction point
- [ ] Do not add an event type to
metabase-types/analytics/event.tsor to any union
Event Schema Types
1. Simple Events (Most Common)
Use SimpleEventSchema for straightforward tracking. It supports these standard fields:
type SimpleEventSchema = {
event: string; // Required: Event name (snake_case)
target_id?: number | null; // Optional: ID of affected entity
triggered_from?: string | null; // Optional: UI location/context
duration_ms?: number | null; // Optional: Duration in milliseconds
result?: string | null; // Optional: Outcome (e.g., "success", "failure")
event_detail?: string | null; // Optional: Additional detail/variant
};
When to use: 90% of events fit this schema. Use for clicks, opens, closes, creates, deletes, etc.
trackSimpleEvent is generic and enforces this schema on the object literal you pass it:
// frontend/src/metabase/analytics/event.ts
export function trackSimpleEvent<
T extends SimpleEventSchema &
Record<Exclude<keyof T, keyof SimpleEventSchema>, never>,
>(event: T) {
trackSchemaEvent("simple_event", event);
}
That means a missing event or any field outside SimpleEventSchema is a compile error at the call
site. There is no separate event type to declare and no satisfies clause to add — the old
ValidateEvent<...> helper is no longer exported and is not part of the workflow.
trackSchemaEvent is generic too: it correlates the schema name with the payload type, so you can't
send a dashboard event under the simple_event schema.
2. Custom Schemas (legacy, no events are being added)
Consider adding new event schema only in very special cases.
Examples: DashboardEventSchema, CleanupEventSchema, QuestionEventSchema
Step-by-Step: Adding a Simple Event
Example: Track when a user applies filters in a table picker
Step 1: Create Tracking Functions
In your feature's analytics.ts file (e.g., enterprise/frontend/src/metabase-enterprise/data-studio/analytics.ts):
import { trackSimpleEvent } from "metabase/analytics";
export const trackDataStudioTablePickerFiltersApplied = () => {
trackSimpleEvent({
event: "data_studio_table_picker_filters_applied",
});
};
export const trackDataStudioTablePickerFiltersCleared = () => {
trackSimpleEvent({
event: "data_studio_table_picker_filters_cleared",
});
};
Step 2: Use in Components
Import and call the tracking function at the interaction point:
import {
trackDataStudioTablePickerFiltersApplied,
trackDataStudioTablePickerFiltersCleared,
} from "metabase-enterprise/data-studio/analytics";
function FilterPopover({ filters, onSubmit }) {
const handleReset = () => {
trackDataStudioTablePickerFiltersCleared(); // <- Track here
onSubmit(emptyFilters);
};
return (
<form
onSubmit={(event) => {
event.preventDefault();
trackDataStudioTablePickerFiltersApplied(); // <- Track here
onSubmit(form);
}}
>
{/* form content */}
</form>
);
}
Using SimpleEventSchema Fields
All examples below live in the feature's own analytics.ts — nothing is registered centrally.
Example: Event with target_id
export const trackDataStudioLibraryCreated = (id: CollectionId) => {
trackSimpleEvent({
event: "data_studio_library_created",
target_id: Number(id),
});
};
// Usage
trackDataStudioLibraryCreated(newLibrary.id);
Example: Event with triggered_from
// Local union, exported only if another feature needs to pass the same value
export type NewButtonLocation = "app-bar" | "empty-collection";
export const trackNewButtonClicked = (location: NewButtonLocation) => {
trackSimpleEvent({
event: "new_button_clicked",
triggered_from: location,
});
};
// Usage
<Button onClick={() => {
trackNewButtonClicked("app-bar");
handleCreate();
}}>
New
</Button>
Example: Event with event_detail
Real example — frontend/src/metabase/metadata/pages/shared/analytics.ts:
export type MetadataEditEventDetail =
| "type_casting"
| "semantic_type_change"
| "visibility_change";
export const trackMetadataChange = (detail: MetadataEditEventDetail) => {
trackSimpleEvent({
event: "metadata_edited",
event_detail: detail,
triggered_from: "admin",
});
};
// Usage
trackMetadataChange("semantic_type_change");
Example: Event with result and duration
See frontend/src/metabase/archive/analytics.ts for the real version of this.
export const trackMoveToTrash = (params: {
targetId: number | null;
triggeredFrom: "collection" | "detail_page" | "cleanup_modal";
durationMs: number | null;
result: "success" | "failure";
itemType: "question" | "model" | "metric" | "dashboard";
}) => {
trackSimpleEvent({
event: "moved-to-trash",
target_id: params.targetId,
triggered_from: params.triggeredFrom,
duration_ms: params.durationMs,
result: params.result,
event_detail: params.itemType,
});
};
// Usage with timing
const startTime = Date.now();
try {
await moveToTrash(item);
trackMoveToTrash({
targetId: item.id,
triggeredFrom: "collection",
durationMs: Date.now() - startTime,
result: "success",
itemType: "question",
});
} catch (error) {
trackMoveToTrash({
targetId: item.id,
triggeredFrom: "collection",
durationMs: Date.now() - startTime,
result: "failure",
itemType: "question",
});
}
Naming Conventions
Event Names (snake_case)
// Good
"data_studio_library_created"
"table_picker_filters_applied"
"metabot_chat_opened"
// Bad
"DataStudioLibraryCreated" // Wrong case
"tablePickerFiltersApplied" // Wrong case
"filters-applied" // Use underscore, not hyphen
Local Field Types (PascalCase, named after the field)
There is usually no ...Event type to name anymore. When you do need a union for a field, name it
after the field it feeds:
// Good
type MetricDimensionResult = "success" | "failure"; // -> result
export type MetadataEditEventDetail = "type_casting"; // -> event_detail
type NewButtonLocation = "app-bar" | "empty-collection"; // -> triggered_from
Tracking Function Names (camelCase with "track" prefix)
// Good
trackDataStudioLibraryCreated
trackTablePickerFiltersApplied
trackMetabotChatOpened
// Bad
DataStudioLibraryCreated // Missing "track" prefix
track_library_created // Wrong case
logLibraryCreated // Use "track" prefix
Common Patterns
Pattern 1: Sharing Field Types Across Features
When two features send the same event with a different triggered_from, export the field union from
the owning feature's analytics.ts and import it — don't hoist anything into metabase-types:
// frontend/src/metabase/data-studio/data-model/analytics.ts
import { trackSimpleEvent } from "metabase/analytics";
import type { MetadataEditEventDetail } from "metabase/metadata/pages/shared/analytics";
export function trackMetadataChange(detail: MetadataEditEventDetail) {
trackSimpleEvent({
event: "metadata_edited",
event_detail: detail,
triggered_from: "data_studio",
});
}
This is the point of the extensible-events design: enterprise and feature-tier types stay in their own module instead of being imported down into a shared union.
Pattern 2: Conditional Tracking
Track different events based on user action:
const handleSave = async () => {
if (isNewItem) {
await createItem(data);
trackItemCreated(newItem.id);
} else {
await updateItem(id, data);
trackItemUpdated(id);
}
};
Common Pitfalls
Don't: Add custom fields to a simple event
// WRONG - SimpleEventSchema doesn't support custom fields (this is a compile error)
export const trackFiltersApplied = (filters: FilterState) => {
trackSimpleEvent({
event: "filters_applied",
data_layer: filters.dataLayer, // ❌ Not in SimpleEventSchema
data_source: filters.dataSource, // ❌ Not in SimpleEventSchema
with_owner: filters.hasOwner, // ❌ Not in SimpleEventSchema
});
};
// RIGHT - Use only standard SimpleEventSchema fields
export const trackFiltersApplied = () => {
trackSimpleEvent({
event: "filters_applied",
});
};
// Or use event_detail for a single variant
export const trackFilterApplied = (filterType: string) => {
trackSimpleEvent({
event: "filter_applied",
event_detail: filterType, // ✓ "data_layer", "data_source", etc.
});
};
Don't: Add event types to metabase-types/analytics/event.ts
The central SimpleEvent union was removed — it forced feature-tier types to be imported down into
shared code, causing module-boundary violations. trackSimpleEvent is generic now, so the type adds
nothing but duplication.
// ❌ WRONG - central declaration + re-import for a `satisfies` clause
// frontend/src/metabase-types/analytics/event.ts
export type NewFeatureClickedEvent = ValidateEvent<{
event: "new_feature_clicked";
target_id: number;
}>;
// frontend/src/metabase/my-feature/analytics.ts
import type { NewFeatureClickedEvent } from "metabase-types/analytics";
export const trackNewFeatureClicked = (id: number) => {
trackSimpleEvent({
event: "new_feature_clicked",
target_id: id,
} satisfies NewFeatureClickedEvent);
};
// ✓ RIGHT - the object literal is already checked by the generic
// frontend/src/metabase/my-feature/analytics.ts
export const trackNewFeatureClicked = (id: number) => {
trackSimpleEvent({
event: "new_feature_clicked",
target_id: id,
});
};
A few ...Event types still sit in metabase-types/analytics/event.ts. They are leftovers from PRs
that landed around the refactor — don't copy them, and don't add to them.
Don't: Mix up event name formats
// WRONG
event: "dataStudioLibraryCreated" // camelCase
event: "data-studio-library-created" // kebab-case
event: "Data_Studio_Library_Created" // Mixed case
// RIGHT
event: "data_studio_library_created" // snake_case
Don't: Track PII or sensitive data
// WRONG - Don't track user emails, names, or sensitive data
trackSimpleEvent({
event: "user_logged_in",
event_detail: user.email, // ❌ PII
});
// RIGHT - Track non-sensitive identifiers only
trackSimpleEvent({
event: "user_logged_in",
target_id: user.id, // ✓ Just the ID
});
Don't: Forget to track both success and failure
// WRONG - Only tracking success
try {
await saveData();
trackDataSaved();
} catch (error) {
// ❌ No tracking for failure case
}
// RIGHT - Track both outcomes
try {
await saveData();
trackDataSaved({ result: "success" });
} catch (error) {
trackDataSaved({ result: "failure" });
}
Testing Analytics Events
While developing, you can verify events are firing:
- Check browser console - When
SNOWPLOW_ENABLED=truein dev, events are logged - Use shouldLogAnalytics - Set in
metabase/envto see all analytics in console - Check Snowplow debugger - Browser extension for Snowplow events
Example console output:
[SNOWPLOW EVENT | event sent:true], data_studio_table_picker_filters_applied
File Organization
Where to put tracking functions:
Tracking functions AND their local field types (this is where new events live):
frontend/src/metabase/{feature}/analytics.ts
enterprise/frontend/src/metabase-enterprise/{feature}/analytics.ts
Core tracking utilities:
frontend/src/metabase/analytics/ (import from `metabase/analytics`)
Shared SimpleEventSchema only — nothing new goes here:
frontend/src/metabase-types/analytics/event.ts
In embedding SDK code, use trackSdkSimpleEvent
(frontend/src/embedding-sdk-bundle/analytics/snowplow.ts) instead — the main-app "sp" tracker
isn't initialized in the customer's page, so trackSimpleEvent's Snowplow leg is a no-op there.
Real-World Examples
See these files for reference:
- Simple events + local field union:
frontend/src/metabase/metadata/pages/shared/analytics.ts - Reusing another feature's field type:
frontend/src/metabase/data-studio/data-model/analytics.ts - Result + duration timing:
frontend/src/metabase/archive/analytics.ts - Enterprise feature events:
enterprise/frontend/src/metabase-enterprise/google_drive/analytics.ts
Workflow Summary
- Identify the user interaction to track
- Decide on event name (snake_case, descriptive)
- Create tracking function in feature's
analytics.ts, callingtrackSimpleEvent() - Add local field unions in that same file if a field has a fixed set of values
- Import and call at the interaction point
- Test that events fire correctly
Tips
- Be specific -
filters_appliedis better thanaction_performed - Use past tense -
library_creatednotcreate_library - Group related events - Keep a feature's tracking functions together in its
analytics.ts - Track meaningful actions - Not every click needs tracking
- Consider the data - What would you want to analyze later?
- Stay consistent - Follow existing naming patterns in the codebase
- Document context - Use
triggered_fromto track where the action happened
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/frontend-analytics-events-mte1lg3b' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/frontend-analytics-events-mte1lg3b/download' --output '.skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md.part' && mv '.skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md.part' '.skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Grep, Glob
Extrait original : Quick Reference
Analytics events in Metabase use Snowplow with typed event schemas. Simple events are declared where they are used — trackSimpleEvent is generic and validates the payload at the call site.
Key Files:
frontend/src/metabase/analytics/event.ts- Core tracking functions,trackSimpleEvent/trackSchemaEvent(import frommetabase/analytics)frontend/src/metabase-types/analytics/event.ts- The sharedSimpleEventSchemaonly. Do not add event types here (see below)frontend/src/metabase-types/analytics/schema.ts- Schema registry (custom/legacy schemas only)- Feature-specific
analytics.tsfiles - Where your tracking functions and any local types live
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md' && test -s '.skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/analytics-events' && cp -R '.skill-downloads/frontend-analytics-events-mte1lg3b' '.claude/skills/analytics-events'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/frontend-analytics-events-mte1lg3b'openskills read 'frontend-analytics-events-mte1lg3b'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/frontend-analytics-events-mte1lg3b/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Bonnes pratiques React Hook Form
Developpement
Maîtrisez React Hook Form : évitez les anti-patterns, gérez les abonnements, et traitez correctement reset, dirty state et entrées contrôlées.
Migration Emotion vers Mantine
Developpement
Migrer les styled-components Emotion vers des composants Mantine avec style props et modules CSS. Pour convertir .styled.tsx ou supprimer les imports @emotion.
Détecteur de dérive de périmètre
Developpement
Analyse les diffs git par rapport à une intention pour détecter la dérive de périmètre, fichiers non liés et PR trop larges, puis suggère de garder, diviser ou justifier.