metabase-data-app-semantic-layer

v2026.09.24

Use when building, creating, or editing data apps that should query Metabase tables and metrics through generated schema files like metabase.data.ts or *.metabase.data.ts.

GitHub
Install command
npx skhub add metabase/metabase-data-app-semantic-layer
Markdown
SKILL.md

Metabase Data App Semantic Layer

Core Rules

Keep the semantic layer and presentation layer separate.

  • All Metabase context must come from the generated schema file, usually src/metabase.data.ts or src/*.metabase.data.ts.
  • Do not discover data through MCP tools, create Metabase content, create tables, or edit the semantic layer while building the React UI.
  • Import data app query helpers from @metabase/embedding-sdk-react/data-app.
  • Every query is a defineQuery(...) named export in the root-level queries/ directory, and every action a defineAction(...) named export in the root-level actions/ directory, both beside package.json. Create both directories before writing the first hook call; the template ships them, each with a README. The hooks enforce this at compile time: useMetabaseQuery, useMetabaseQueryObject, and useAction reject an inline object, a satisfies MetabaseQueryOptions object, and a spread copy of a definition. The error reads Property 'definedWithDefineQuery' is missing (or 'definedWithDefineAction'); the fix is always to move the object into queries/ or actions/ as a definition and import it, never a cast.
  • Never remove, edit, or copy a generated savedQuestionSourceId or copiedActionId, even if it appears unused. Preserve it during refactors; use npm run sync-resources to repair or replace generated IDs.
  • Prefer generated schema objects over raw IDs or strings. Extract local constants for top-level table objects.
  • Never hand-write DatasetQuery/MBQL objects in app code. Do not pass inline query objects like { type: "query", query: { "source-table": table.id } }, raw source-table clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, useMetabaseQuery, or useMetabaseQueryObject. Prefer generated table and metric schema objects; for simple table-source queries, an explicit source reference like { type: "table", id: table.id } is also valid.
  • Build queries with source: schema.tables.<name>, generated fields, generated segments, generated measures, generated metrics in aggregations, generated metric dimensions, filter(...), breakout(...), orderBy(...), and aggregations helpers such as aggregations.count() and aggregations.sum(...). Do not use source: schema.metrics.<name>; metrics are aggregation expressions, not query sources.
  • Do not use existing saved questions as useMetabaseQuery or useMetabaseQueryObject sources. Typed schemas do not expose schema.questions or support question-collections while data-app reconciliation cannot copy existing saved questions into the app collection.
  • Prefer semantically rich table queries over shallow table dumps. Use curated table measures, segments, filters, and breakouts when they make the generated app more useful.
  • Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows. Both belong to the static query only — the dynamic second argument cannot take them, see Static and dynamic query parts.
  • Filter UI must default to showing data. Empty controls, "All" options, and incomplete custom ranges should produce no filter instead of blocking queries or showing a blank dashboard.
  • Do not hardcode categorical filter option values. A generated schema field only proves the field exists, not which values exist; query options from Metabase at runtime using the same generated schema field that the filter applies.
  • Dashboard-level filters should visibly affect every compatible card, table, KPI, and trend. If a filter can only apply to one query, make that scope obvious in the UI; do not show duplicate or no-op date controls.
  • Entity filters, where the stored value is an id/key and the UI shows a label, must use a single searchable combobox. Click/focus must open the option list immediately, before typing. Query options at runtime, search labels, and store the raw value. Never render entity filters as <select>; plain selects are only for short closed enums explicitly provided by the user.
  • Use DateRangePopover from @metabase/embedding-sdk-react/data-app for custom date ranges: it wraps the app's own trigger element and opens a Metabase-styled range calendar under it. The trigger stays the app's — style it like the other filter controls — and useDateFormatter() from the same entry produces its label. It ships with the SDK and needs no dependency and no CSS import. DateRangeCalendar is the same calendar inline, for when the app already has a container. Do not install a date picker library for a range — not react-datepicker, react-day-picker, flatpickr, or a UI suite's picker (@mui/x-date-pickers, antd, rsuite, …). Do not use native <input type="date"> either: its placeholder and calendar popover are browser-controlled, often show mm/dd/yyyy, and cannot be reliably themed.
  • Never build a date label with new Date("YYYY-MM-DD") — a date-only string parses as UTC and shows the previous day west of Greenwich. Use formatDateRange / formatDate from useDateFormatter(), which parse in local time and format in the instance's locale.
  • Reach for a third-party date picker only for what the SDK calendar does not cover, such as single-date or date-time selection; react-datepicker is the default pick. Then import its stylesheet (react-datepicker/dist/react-datepicker.css), add small CSS overrides for the app's visual style if needed, and pass Date | null — never new Date("") or another invalid date for incomplete ranges; type strict callback parameters explicitly, such as onChange={(date: Date | null) => ...}.
  • Date bars must include Custom last by default: duration presets, All time, then Custom. Omit Custom only when the user explicitly asks for fixed presets only or no date range control.
  • Never invent aggregation or measure objects such as { name: "count" } or { name: "sum", field: ... }. Use generated table measures or exported aggregation helpers.
  • Only render values returned by Metabase or deterministic transforms of returned values. Do not invent KPI values, trends, labels, statuses, ratings, timestamps, rankings, insights, segments, or chart series.
  • Do not custom-render ambiguous business fields such as margin, rate, score, percent, health, risk, or efficiency. Do not add %, multiply by 100, color-code, or render stars unless semantic-layer units explicitly support it; use an SDK table/chart, omit the field, or ask for curation.
  • Visualization data must come from Metabase through useMetabaseQuery or useMetabaseQueryObject with InteractiveQuestion/StaticQuestion. Do not hardcode chart-ready arrays, sample data, demo values, or schema-shaped mock values.
  • Render charts with InteractiveQuestion/StaticQuestion. When a custom visualization is allowed instead, and which of the two to use, is decided by the setup skill's Rendering a chart: Metabase first.
  • useMetabaseQueryObject(...) returns { query, error, isLoading }. Pass only the query property as card={{ query }} to InteractiveQuestion or StaticQuestion; never pass the whole hook result as card.query.
  • useMetabaseQuery().rows are keyed objects, not tuple arrays. Never read row[0] / row[1], and never silence this with as unknown as [string, number][], DisplayRow, or another tuple cast. If TypeScript says property 0 does not exist, it is catching a real bug. For typed data.rows, use literal keys such as row.count or generated field names such as row[ordersTable.fields.createdAt.name]. Use data.columns with rawRows or after explicitly narrowing a key; do not index typed rows with arbitrary string values from data.columns.
  • Do not cast query objects to Parameters<typeof useMetabaseQuery>[0] or to DefinedQuery. That erases the generated table/metric validation and the definition contract. Validate table ownership at the definition with defineQuery<typeof table>(...); the hooks take the export with no generics.
  • Do not build shared filter arrays with ReturnType<typeof filter>[] or push(...); this can collapse overload inference. Pass raw filter state between components and build each query's filters: [...] inline with spreads.
  • Keep runtime state out of the base query in queries/. A clause whose value comes from a control — a selected plan, a date range, a search box — belongs in the second argument to useMetabaseQuery/useMetabaseQueryObject, not in the query. See "Static and dynamic query parts".
  • Do not include fields in queries with aggregations and breakouts; breakouts determine grouped result columns. Use fields only for row-selection queries.
  • Before rendering a field, verify it exists in the generated schema object and is returned by the query. Do not guess table keys, field keys, or column names from the Metabase API, business intuition, or old mock data; only use entries actually emitted in src/metabase.data.ts.
  • Avoid unsupported freshness or operational claims such as "real-time", "live", "understaffed", or "risk" unless the returned data or curated semantic-layer definition supports them.
  • Before claiming the work is done or preparing a final handoff, run a TypeScript type-only check and report the command/result. If the check fails, fix the type errors before any final summary.

Generate Schema

If the schema file already exists, use it. If it is missing or stale, treat schema generation as semantic-layer curation for this data app, not a mechanical export.

Choose the export scope before generating:

  1. Honor an explicit scope. Otherwise infer the required content types from the app's purpose: tables, curated metrics, or actions. For example, "show orders" needs tables; row counts and sums can also use table aggregations.
  2. Choose the narrowest supported scope that covers those needs, using collection IDs and database names or IDs from the request or project context. When the library type is clear but a narrower collection is unknown, use that library's whole tree.
  3. Ask only for context needed to select a scope, such as which database to use when the request requires a database scope but does not identify one. Once the scope is determined, state it briefly and generate without waiting for confirmation.

Scope parameters:

  • include-data-library=true for the whole Library / Data tree.
  • include-metric-library=true for the whole Library / metrics tree.
  • library-collections=<id-or-entity-id>[,<id-or-entity-id>] for specific Data or metrics library subcollections.
  • include-models=true for readable models that have actions. When combined with database=<name-or-id>, it includes models with actions for that database only.
  • database=<name-or-id> when the app should use tables from one database. Use it separately from library scopes; the API rejects that combination.

Combine library scopes when the app needs both tables and curated metrics.

Use include-models=true when the app needs any saved action under schema.models.<model>.actions; it includes all readable models with executable actions, unless database scopes them to one database. Models without executable actions are omitted to keep generated schemas compact. It can be combined with library-collections, include-data-library, or include-metric-library so one schema can include selected tables/metrics plus all readable actions.

If the user asks for any mutation-like flow, such as creating, updating, deleting, submitting, approving, executing an action, or running a write operation, include include-models=true in the typed-schema URL. Do this even when the user names one specific model/action, because actions are only discoverable through generated model entries.

The Metabase URL and API key live in the repo-root .env.local as DATA_APP_MB_URL and DATA_APP_MB_API_KEY (one file per repo, usually two levels up from the app dir, not in the app dir). The command below sources that file so the shell substitutes the values straight into curl — you never read, extract, or handle the credentials yourself.

Never ask the user to paste the API key into the chat, and never cat / echo .env.local — it's git-ignored and may hold other secrets, so its contents must stay out of the conversation. source it so the shell uses the values without exposing them. If $DATA_APP_MB_API_KEY or $DATA_APP_MB_URL is empty or still set to the default mb_replace_me placeholder after sourcing, ask the user to add real values themselves, then continue.

Source the credentials from the repo-root .env.local and generate the scoped schema. The example below exports table data from the Data library; replace its query parameters with the scope chosen above:

ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
if [ -z "$ROOT" ]; then
  echo "Not inside the connected git repo — cd into it first." >&2
  exit 1
fi

(
  source "$ROOT/.env.local" 2>/dev/null
  # Fail early (before curl) if either var is missing or placeholder-only.
  if [ -z "$DATA_APP_MB_URL" ] || [ "$DATA_APP_MB_URL" = "mb_replace_me" ] ||
     [ -z "$DATA_APP_MB_API_KEY" ] || [ "$DATA_APP_MB_API_KEY" = "mb_replace_me" ]; then
    echo "Set real DATA_APP_MB_URL / DATA_APP_MB_API_KEY in repo-root .env.local" >&2
    exit 1
  fi
  curl \
    -o src/metabase.data.ts \
    -H "x-api-key: $DATA_APP_MB_API_KEY" \
    -H "Accept: text/typescript" \
    "$DATA_APP_MB_URL/api/typed-schemas/v1/typescript?include-data-library=true"
)

After a successful export, verify that the schema contains every entity needed for the requested app. If any are missing, revise the scope using available context or ask for the missing context before building the UI.

If schema generation fails while building a selected model or model action, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing card-id / card-name / card-type, model-id / model-name, dropped action ids, and message when present.

Synchronize every query and action

Everything an end-to-end prototype runs is permission-bound: it runs against a copy in the app's own collection; read access to that collection lets viewers run the app's cards, but they see the data only if they already have access to the underlying tables — the app grants the collection, not the tables. Declare each one as a named export in a root-level directory beside package.json — queries/ for defineQuery(...), actions/ for defineAction(...). npm run sync-resources scans only those two directories, so a definition under src/queries/, src/actions/, or any other source directory is silently never synchronized. Discovery covers .js, .jsx, .ts, .tsx, .cjs, .cts, .mjs, and .mts.

import { defineAction, defineQuery } from "@metabase/embedding-sdk-react/data-app";
import schema from "../src/metabase.data";

// queries/revenue.query.ts
export const RevenueQuery = defineQuery({ source: schema.tables.orders });

// actions/orders.action.ts
export const CreateOrder = defineAction({
  action: schema.models.orders.actions.create,
});

One sync-resources run reconciles both. For a query it materializes the authored table query as a saved question and injects savedQuestionSourceId. For an action it copies the action's parent model into the app collection, copies the action onto that copy, and injects copiedActionId; a model is copied once no matter how many of its actions the app declares, siblings reuse that copy, and it disappears with the last declaration. Never copy a model into the app collection by hand.

Pass the definition itself to the hook and let the SDK resolve what runs — a production build runs the copy, while the dev preview runs the authored table or action, so an app works before its first synchronization:

const { data } = useMetabaseQuery(RevenueQuery, {
  filters: [filter(RevenueQuery.source.fields.status, "=", selectedStatus)],
});

const { execute, isExecuting, error } = useAction(CreateOrder);

Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, savedQuestionSourceId, copiedActionId, or a hand-built { source: { type: "card", id } }, and never spread a definition into a new object. Each defeats the swap; the authored ids also bypass the permission boundary. TypeScript rejects most of these: the hooks accept only what defineQuery/defineAction returned, so an inline object, a satisfies-typed object, a spread copy, and schema.models.<model>.actions.<action> all fail to compile. When tsc reports Property 'definedWithDefineQuery' is missing or Property 'definedWithDefineAction' is missing, the argument is not a definition: move it into queries/ or actions/ and import the export. Do not silence it with a cast or by wrapping the inline object in defineQuery(...) at the call site, which compiles but leaves the query unsynchronized. Keep fixed permission-boundary filters, aggregations, and breakouts inside defineQuery — synchronization bakes them into the saved question, so don't apply them again outside it, and put runtime clauses in the hook's second argument (see Static and dynamic query parts). useAction needs no generics: the definition types execute's parameters and result.

Wire package.json with "sync-resources": "embedding-sdk-react data-apps sync-resources" and "build": "npm run sync-resources && vite build", then run npm run build after adding, changing, renaming, or removing any definition; run sync-resources directly only to inspect generated state before a build. It reads DATA_APP_MB_URL and DATA_APP_MB_API_KEY from the repo-root .env.local.

Inline generated IDs and resources_metadata.json are generated state: never delete or hand-edit either. A missing ID is restored automatically when the definition still identifies its resource — a query by its table and authored hash matching one unclaimed lockfile entry, an action by naming the same action — while a duplicated ID fails the run. Do not test or hand off the app until npm run build succeeds, every live definition carries a positive generated ID, and resources_metadata.json holds its matching entry. Commit every generated change. The build stops before bundling when synchronization fails.

If synchronization fails, surface the exact error and stop. Fix local shape, serialization, duplicate-ID, or lockfile errors before retrying. A confirmed 404 is recovered automatically; authentication, permission, network, server, collection-ownership, and Card-type failures must not trigger manual Card creation, deletion, ID replacement, or lockfile editing. Treat a successful run that discovers nothing as a failure when the app has queries or actions. Synchronization copies actions but never creates them, so an action the app needs must already exist in Metabase and be picked up by a regenerated schema; if the run reports that actions are not enabled for the database, stop and tell the user to enable them rather than working around it.

Standard pattern

Two files per query: the definition in queries/, the hook call in the component.

// queries/orders.query.ts
import {
  aggregations,
  breakout,
  defineQuery,
  filter,
  orderBy,
} from "@metabase/embedding-sdk-react/data-app";
import schema from "../src/metabase.data";

const ordersTable = schema.tables.orders;

export const PaidRevenueByMonth = defineQuery({
  source: ordersTable,
  filters: [
    ordersTable.segments.completed,
    filter(ordersTable.fields.status, "=", "paid"),
  ],
  aggregations: [aggregations.sum(ordersTable.fields.amount)],
  breakouts: [breakout(ordersTable.fields.createdAt, { unit: "month" })],
  orderBys: [orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" })],
  limit: 100,
});
// src/pages/Overview.tsx
import { useMetabaseQuery } from "@metabase/embedding-sdk-react/data-app";
import { PaidRevenueByMonth } from "../../queries/orders.query";

const { data, isLoading, error } = useMetabaseQuery(PaidRevenueByMonth);

useMetabaseQuery(...) infers typed row data from the definition, so write no generics on the hook. To check table ownership of fields, segments, and measures, put the generic on the definition: defineQuery<typeof ordersTable>({ ... }). Leave it off selected-field queries when you need precise row keys from data.rows. The recipes below show the object passed to defineQuery; each one is an export in queries/, never an argument written at the hook.

Call each schema entry at most once per render tree. Multiple useMetabaseQuery calls on the same questionId (or same tableId + identical filters/measures/breakouts) mount independent subscriptions, fire duplicate queries, and let consumers disagree mid-load. Lift the call to the highest component that needs the data; pass data / isLoading / error down as props. Different ids — or the same id with different filters / breakouts — are different data sources; call them separately.

Use keyed schema objects:

  • Tables: source: schema.tables.<table>
  • metrics: schema.metrics.<metric> inside aggregations
  • Fields: schema.tables.<table>.fields.<field>
  • Segments: schema.tables.<table>.segments.<segment>
  • Measures: schema.tables.<table>.measures.<measure>
  • metric dimensions: schema.metrics.<metric>.dimensions.<group>.<dimension>

Do not pass raw dimension strings like "created_at" or "segment".

Static and dynamic query parts

Both query hooks take an optional second argument: the clauses that change while the app runs.

// revenue.query.ts — static, and identical on every render
const orders = schema.tables.orders;

export const RevenueQuery = defineQuery({
  source: orders,
  aggregations: [aggregations.sum(orders.fields.total)],
  breakouts: [
    breakout(orders.fields.createdAt, { unit: "month" }),
    breakout(orders.fields.plan),
  ],
});

// the component supplies only what the UI changes
const { data } = useMetabaseQuery(RevenueQuery, {
  filters: plan === null ? [] : [filter(orders.fields.plan, "=", plan)],
});

Split them this way even when nothing appears to depend on it: the first argument must be identical on every render, and only the second may vary with runtime state.

The dynamic clauses run as their own stage, so they see the result columns of the static query, not its source table. That is why plan is a breakout above: a control that filters on a source column only works if that column survives into the result. If it does not, add it as a breakout, or leave the static query unaggregated. Likewise, filter an aggregated static query on count/sum, not on the fields behind them.

Segments and measures belong to the static part only. They are defined against a table, and the dynamic stage has no table — so filters: [orders.segments.completed] and aggregations: [orders.measures.revenue] are rejected, at compile time and again at runtime. This is the one place the usual "prefer the curated definition" rule does not apply.

Put the curated definition in the static query where it resolves, and let the dynamic clause work on what came out:

export const CompletedOrders = defineQuery({
  source: orders,
  filters: [orders.segments.completed], // the segment resolves here
  aggregations: [orders.measures.revenue],
  breakouts: [breakout(orders.fields.plan)],
});

const { data } = useMetabaseQuery(CompletedOrders, {
  // a result column, not a segment or measure
  filters: plan === null ? [] : [filter({ type: "column", name: "PLAN" }, "=", plan)],
});

If a control must switch a segment on and off, that is a choice between static queries, not a dynamic clause: define one query per state and pick the query, or express the same condition as a filter on a result column.

Do not remove or hand-edit savedQuestionSourceId if you find it on a query object, or copiedActionId on an action definition. Both are generated synchronization state — see Synchronize every query and action.

Table query recipes

For a table query, pass the generated table object as source:

// queries/records.query.ts
const recordsTable = schema.tables.records;

export const RecordStatuses = defineQuery({
  source: recordsTable,
  fields: [recordsTable.fields.id, recordsTable.fields.status],
});

For grouped table summaries, include at least one aggregation:

export const ActiveAmountByMonth = defineQuery({
  source: recordsTable,
  filters: [
    recordsTable.segments.activeRecords,
    filter(recordsTable.fields.amount, ">", 100),
  ],
  aggregations: [recordsTable.measures.totalAmount],
  breakouts: [breakout(recordsTable.fields.createdAt, { unit: "month" })],
  orderBys: [orderBy(recordsTable.fields.createdAt, "desc", { unit: "month" })],
});

For basic aggregations without a curated measure, use the aggregations helpers:

export const AmountByCategory = defineQuery({
  source: recordsTable,
  aggregations: [
    aggregations.count(),
    aggregations.sum(recordsTable.fields.amount),
  ],
  breakouts: [breakout(recordsTable.fields.category)],
});

When using the same helper more than once, Metabase may return numbered runtime keys such as sum, sum_2, and sum_3. TypeScript only models the base helper key today. For custom KPI code that intentionally uses repeated same-kind aggregations, read through data.columns or cast the row to Record<string, unknown> before accessing numbered keys. Prefer curated measures or separate queries when that is clearer.

Table fields, segments, measures, filters, breakouts, and orderBys must come from the queried table. Use defineQuery<RecordsTable>({ ... }) when you want TypeScript to validate that ownership at the definition.

metric aggregation recipes

For a metric-backed query, pass the generated table object as source and the generated metric object in aggregations:

// queries/revenue.query.ts
const ordersTable = schema.tables.orders;
const revenueMetric = schema.metrics.revenue;

export const Revenue = defineQuery({
  source: ordersTable,
  aggregations: [revenueMetric],
});

Use generated metric dimensions for filters and breakouts in queries that aggregate the owning metric. Dimensions from the metric's source table work directly. Dimensions from related tables also work when the generated field includes sourceFieldId; prefer those related-table dimensions for readable labels instead of grouping by raw foreign key IDs:

export const PaidRevenueByMonthAndFranchise = defineQuery({
  source: ordersTable,
  aggregations: [revenueMetric],
  filters: [filter(revenueMetric.dimensions.orders.status, "=", "paid")],
  breakouts: [
    breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" }),
    breakout(revenueMetric.dimensions.franchises.name),
  ],
  orderBys: [
    orderBy(revenueMetric.dimensions.orders.createdAt, "desc", {
      unit: "month",
    }),
  ],
});

// Prefer readable related-table dimensions when available.
breakout(revenueMetric.dimensions.franchises.name);

// Avoid raw FK IDs when the related-table dimension exists.
breakout(revenueMetric.dimensions.orders.franchiseId);

Queries backed by metrics can include helper aggregations over generated metric dimensions. They can also use compatible saved Segments and Measures from the table source when the generated schema exposes them:

export const CompletedRevenueByStatus = defineQuery({
  source: ordersTable,
  filters: [schema.tables.orders.segments.completed],
  aggregations: [
    revenueMetric,
    schema.tables.orders.measures.totalRevenue,
    aggregations.sum(revenueMetric.dimensions.orders.amount),
  ],
  breakouts: [breakout(revenueMetric.dimensions.orders.status)],
});

A metric aggregation must belong to the table source. Do not use source-card metrics in table-source queries. Generated metric dimensions are scoped to their owning metric: if a query uses revenueMetric.dimensions.* in filters, helper aggregations, breakouts, or orderBys, it must also include revenueMetric in aggregations. Do not use metric dimensions as standalone table fields for unrelated count() or table-measure queries. Generated metric dimensions must also resolve to the table source. Use defineQuery<typeof ordersTable>({ ... }) when you want TypeScript to validate that at the definition.

SDK-rendered views

Table fields, segments, measure aggregations, and metric aggregations must come from the queried table. Generated metric dimensions used in filters, helper aggregations, breakouts, and orderBys must resolve to the queried table and belong to a metric included in the same query's aggregations. When table queries use fields, segments, aggregations, breakouts, or orderBys, let defineQuery infer the shape, or write defineQuery<typeof recordsTable> when ownership validation matters more than precise result-row keys.

Interactive Metabase Views

Whether an element is an SDK question at all — and whether it is StaticQuestion or InteractiveQuestion — is decided in the data-app setup skill (Rendering a chart: Metabase first). Once it is: declare the query in queries/, resolve it with useMetabaseQueryObject(TheQuery), then pass the result through the SDK question component's card prop.

useMetabaseQueryObject supports generated table queries, including metric aggregations. Use useMetabaseQuery when custom React needs direct row data; use useMetabaseQueryObject when Metabase should render or manage the visualization. Do not pass generics to useMetabaseQueryObject; it returns { query, error, isLoading }, not query result rows.

The examples under Rendering With SDK Components use return null for minimal loading and error handling. In a real app, render the app's existing loading or error UI there. Passing card={{ query }} is safe while query is null; do not pass the full { query, error, isLoading } hook result as card.query.

When wrapping useMetabaseQueryObject in a reusable chart/card component, destructure and render error; do not read only { query }, because query-construction failures otherwise look like endless loading. Calling the hook inside that child component is valid React. Do not call hooks directly inside loops, conditions, or callbacks in the parent component.

Wrong/right pattern:

const trendQuery = useMetabaseQueryObject(TrendQuery);
<InteractiveQuestion card={{ query: trendQuery }} />; // wrong

const { query: trendQuery } = useMetabaseQueryObject(TrendQuery);
<InteractiveQuestion card={{ query: trendQuery }} />; // right

Hook typing:

  • Both hooks take a defineQuery export imported from queries/ and nothing else; an inline object is a compile error. Write no generics on the hooks.
  • useMetabaseQuery(...) infers typed row data from the definition. Put defineQuery<typeof table> on the definition when ownership validation matters.
  • useMetabaseQueryObject(...) returns { query, error, isLoading }. Pass the query property to card={{ query }}.
  • Do not use as Parameters<typeof useMetabaseQuery>[0] or as DefinedQuery to quiet query typing errors. The first hides invalid table fields, metric aggregations, and breakouts; the second hides an unsynchronized query that fails in production.

The basic prop contract is:

  • Generated table query, including metric aggregations: <StaticQuestion card={{ query }} />
  • Full interactive question: <InteractiveQuestion card={{ query }} />

When you need the set of SDK-supported question displays, do not copy a local list. In generated apps, search node_modules/@metabase/embedding-sdk-react/dist/index.d.ts for the exact declaration declare const cardDisplayTypes: readonly [...] and use that tuple as the source of truth. Do not read the whole declaration file into context.

Always pass SDK-rendered ad hoc questions with a card object. Start with card={{ query }} when the user has not asked for a specific chart type and Metabase defaults can infer a reasonable display from the query. Use card={{ query, visualization }} when the user request or design calls for a specific chart type, such as a pie chart for a distribution, but does not ask for setting-level customization. Add visualizationSettings only when the user explicitly asks for a setting-level presentation change, such as hiding or renaming an axis label, showing value labels, stacking bars, adding a goal line, ordering table columns, showing pie totals/labels, or controlling series/slice order. Search node_modules/@metabase/embedding-sdk-react/dist/index.d.ts for export declare type MetabaseCard, the relevant *VisualizationSettings type, and any setting key you plan to use. Read the JSDoc comments attached to those declarations, then use the TypeScript declarations as the source of truth for legal visualization and visualizationSettings combinations. Build the query with useMetabaseQueryObject; do not call internal query resolution helpers, cast through any, or hardcode settings from memory.

For lightweight descriptions of the exposed settings and when to use them, read references/visualization-settings.md. Treat that file as guidance only; the installed SDK declaration decides what is legal.

Before writing a card, check node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts for the useMetabaseQueryObject return type. Destructure the returned query and use that value in card.query; for configured cards, type the object with satisfies MetabaseCard. If TypeScript reports duplicate opaque DatasetQuery symbols, do not force a cast; update the SDK package before using card.

Do not invent alternate prop names for generated queries or visualization settings. If the SDK type says a prop does not exist, believe it and use the documented card prop shape.

When useMetabaseQuery is needed, map typed rows into an explicit local view model using named properties before rendering:

const orderedAtKey = ordersTable.fields.orderedAt.name;

const chartRows = (data?.rows ?? []).map((row) => ({
  label: String(row[orderedAtKey] ?? "Unknown"),
  value: row.count,
}));

If the result key only comes from data.columns at runtime, use rawRows with the matching column position, or narrow the key to a literal before indexing data.rows.

Rendering With SDK Components

Chart only, without the toolbar:

import {
  InteractiveQuestion,
  StaticQuestion,
  type MetabaseCard,
} from "@metabase/embedding-sdk-react";

import { useMetabaseQueryObject } from "@metabase/embedding-sdk-react/data-app";

import { AmountByMonth } from "../../queries/events.query";

const { query, isLoading, error } = useMetabaseQueryObject(AmountByMonth);

if (error) {
  return null;
}

if (isLoading || !query) {
  return null;
}

return (
  <InteractiveQuestion card={{ query }}>
    <InteractiveQuestion.QuestionVisualization height="500px" />
  </InteractiveQuestion>
);

Configured SDK visualization:

// queries/events.query.ts
export const TotalAmountByMonth = defineQuery({
  source: eventsTable,
  aggregations: [eventsTable.measures.totalAmount],
  breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],
});

// the component
const { query, isLoading, error } = useMetabaseQueryObject(TotalAmountByMonth);

if (error) {
  return null;
}

if (isLoading || !query) {
  return null;
}

const trendCard = {
  query,
  visualization: "bar",
  visualizationSettings: {
    "graph.show_values": true,
    "graph.y_axis.title_text": "Total amount",
  },
} satisfies MetabaseCard;

return (
  <InteractiveQuestion card={trendCard}>
    <InteractiveQuestion.QuestionVisualization height="500px" />
  </InteractiveQuestion>
);

Filters And Breakouts

Use helpers because they give better autocomplete and shorter errors.

filter(ordersTable.fields.quantity, ">", 0);
filter(ordersTable.fields.status, "contains", "paid");
filter(ordersTable.fields.quantity, "between", [10, 20]);
filter(ordersTable.fields.status, "not-empty");

breakout(ordersTable.fields.createdAt, { unit: "month" });
breakout(ordersTable.fields.amount, {
  binning: { strategy: "num-bins", "num-bins": 10 },
});
breakout(ordersTable.fields.state);

orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" });

Do not hand-write orderBys object literals such as { field, direction } or { fieldId, direction }; use orderBy(...). When ordering the same date field used by a date breakout, pass the same unit to both breakout(...) and orderBy(...).

For top-N grouped summaries, order by the aggregation result, not the raw source field. Store the aggregation helper in a local constant and pass that same constant to both aggregations and orderBy(...):

// queries/inventory.query.ts
const avgQuantity = aggregations.avg(inventoryTable.fields.quantityOnHand);

export const TopIngredientsByQuantity = defineQuery({
  source: inventoryTable,
  aggregations: [avgQuantity],
  breakouts: [breakout(inventoryTable.fields.ingredient)],
  orderBys: [orderBy(avgQuantity, "desc")],
  limit: 15,
});

For user-selectable sorting, the sort is runtime state, so it belongs in the hook's second argument. Build a typed map of allowed generated fields instead of indexing the whole fields object:

type SortKey = "revenue" | "orders";
type ScorecardTable = typeof scorecardTable;

type ScorecardField = ScorecardTable["fields"][keyof ScorecardTable["fields"]];

const sortFields = {
  revenue: scorecardTable.fields.netRevenue,
  orders: scorecardTable.fields.orders,
} satisfies Record<SortKey, ScorecardField>;

const { data } = useMetabaseQuery(Scorecard, {
  orderBys: [orderBy(sortFields[sortKey], "desc")],
});

Scorecard is the unaggregated defineQuery({ source: scorecardTable }) export in queries/; its source fields survive into the result, so the dynamic stage can order by them.

For metric queries, pass generated metric dimensions to filter(...) and breakout(...):

filter(revenueMetric.dimensions.orders.status, "=", "paid");
breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" });

Filter operator rules:

  • string: =, !=, contains, does-not-contain, starts-with, ends-with, is-empty, not-empty, is-null, not-null
  • number: =, !=, >, >=, <, <=, between, is-null, not-null
  • date: =, !=, >, >=, <, <=, between, time-interval, is-null, not-null
  • boolean: =, is-null, not-null

Only date dimensions can use unit. Non-date dimensions can be used as breakouts without unit; numeric dimensions can use binning.

Segments are already filters:

filters: [
  schema.tables.records.segments.activeRecords,
  filter(schema.tables.records.fields.amount, ">", 100),
];

Use curated segments first when they exactly match the product intent. Use filter(...) when the UI needs a threshold, category, date range, text match, boolean condition, or other narrowing that is not already represented by a curated segment.

Filter UI Patterns

When the user asks for custom filters, build normal React controls that feed semantic query filters.

Before implementing filters, create a filter contract for the visible dashboard. At minimum, identify:

  • For each filter, name the runtime query that provides its options.
  • For each filter, name the raw value used in filter(...).
  • For each card, table, KPI, and trend, name the generated table field or metric dimension that can receive that filter.
  • If a filter only applies to one section, keep it section-scoped or omit it from the global filter bar.
  • If a page needs a different date field such as snapshotDate, use one visible date control for that page.
  • KPI/detail pairs that describe the same concept should use the same relevant filters.

Use the detailed checklist in references/filter-ui-patterns.md for filter state rules, runtime categorical options, stale option reset, searchable controls, and custom date-picker implementation.

For the common memoized date/category filter shape:

type DatePreset = "30d" | "90d" | "custom" | "all";

const [datePreset, setDatePreset] = useState<DatePreset>("all");
const [customRange, setCustomRange] = useState<[string | null, string | null]>([
  null,
  null,
]);
const [status, setStatus] = useState("all");

const dateRange = useMemo((): readonly [string, string] | null => {
  if (datePreset === "all") {
    return null;
  }

  if (datePreset === "custom") {
    const [start, end] = customRange;
    return start && end ? [start, end] : null;
  }

  return getPresetDateRange(datePreset);
}, [datePreset, customRange]);

const orderFilters = useMemo(
  () => [
    ...(dateRange
      ? [filter(ordersTable.fields.createdAt, "between", dateRange)]
      : []),
    ...(status === "all"
      ? []
      : [filter(ordersTable.fields.status, "=", status)]),
  ],
  [dateRange, status],
);

customRange above is what <DateRangePopover value={customRange} onChange={setCustomRange}> stores, so there is nothing to convert. When a fallback picker's state uses Date | null, convert selected dates with a local YYYY-MM-DD formatter before passing them to filter(..., "between", range). Do not use date.toISOString().split("T")[0] for local date filters.

Result Shape And Charts

  • Prefer keyed data.rows.
  • Never treat data.rows as positional arrays. Do not use row[0], row[1], DisplayRow, or tuple casts for useMetabaseQuery row objects.
  • Inspect data.columns before mapping low-level rawRows, but do not use arbitrary data.columns[].name strings to index typed data.rows.
  • Runtime row objects are keyed by returned Metabase column names, usually column.name such as total_amount or average_score. Do not assume generated schema keys like totalAmount or averageScore are runtime row keys.
  • For generated field references, the React property path and runtime result key can differ: schema.tables.orders.fields.orderedAt.name might be ordered_at. Use row[ordersTable.fields.orderedAt.name], row.count, or data.columns metadata instead of guessing row.orderedAt.
  • Treat row values as nullable. Guard before calling number/string methods such as toFixed, toLocaleString, or string transforms.
  • Use rawRows only for known positional shapes.
  • Aggregation columns may be named count, sum, or avg; match metadata when needed.
  • If a custom visualization needs several helper aggregations with the same output name, such as multiple aggregations.sum(...) calls, prefer separate single-aggregation queries so each typed row has the known sum key. If one multi-aggregation query is necessary, read rawRows by column position after checking data.columns; do not depend on generated names like sum_2 unless they are explicitly typed or narrowed in the app code.
  • Grouped queries can include a null breakout bucket. Render it as "Unknown" or filter it out deliberately.
  • Time-series charts need multiple ordered buckets. Do not fake sparklines for scalar or one-point results.
  • Multi-series charts with different units or magnitudes need separate axes or normalization.
  • Format user-facing values: currency to at most 2 decimals, counts as whole numbers, dates as readable labels.
  • Do not render ambiguous derived business values unless the semantic layer description or inspected sample values make the meaning and units obvious.
  • Empty results are distinct from loading. After isLoading is false, render a clear empty state instead of leaving a skeleton or blank KPI.

Presentation Guidance

Prefer Metabase-rendered panels for chart-shaped and table-shaped data. The React app may group, sort, format, and derive display-only values from data.rows when a custom panel is justified, but do not make custom panels the default.

Good transforms:

  • Group rows for summaries.
  • Sort and slice rows for ranked lists only when a custom list is clearly better than a Metabase row/bar/table visualization.
  • Pick chart types from actual data shape, and prefer Metabase bar, line, area, row, combo, pivot, and table displays before writing custom chart code.
  • Show loading, error, and empty states.
  • Bound dense result displays. Tables, alert lists, logs, and ranked lists should use a top-N slice, grouping, pagination, or a fixed/max-height scroll area so a large result set cannot stretch the entire page.

When a page feels like a raw table browser, look for schema-backed ways to enrich it:

  • Use segments for curated subsets like active, completed, overdue, high-priority, or needs-attention records.
  • Use measures for curated aggregations instead of recalculating everything ad hoc in React.
  • Use metrics when the schema exposes a curated metric aggregation for the page's core business question.
  • Use filters to focus the query on the UI's intent.
  • Use breakouts to create trends, category comparisons, and grouped summaries.
  • If the enriched result is still a sortable/drillable table, render it with SDK visualization components instead of rebuilding table behavior in React.

Avoid manual classification when the semantic layer already has the concept. Prefer curated segments, fields, or measures over string matching, threshold heuristics, or category reconstruction in React.

If no curated schema entry supports the intended UI, leave the section out or ask for semantic-layer curation. Do not keep mock data or placeholder analytics in the finished app.

Final Checks

  • Run npm run typecheck. Property 'definedWithDefineQuery' is missing or Property 'definedWithDefineAction' is missing means a hook received something other than a queries/ or actions/ export; move the object there and import it.
  • Search touched files for useMetabaseQuery(, useMetabaseQueryObject(, and useAction(. The first argument must be an identifier imported from queries/ or actions/; a {, a defineQuery(, a defineAction(, or a spread there is wrong even when it compiles. The second argument of the query hooks is the dynamic object and is written inline.
  • Confirm queries/ and actions/ sit beside package.json, not under src/, and that every definition the app renders lives there.
  • Run npm run build; it synchronizes queries before producing the bundle.
  • Keep TypeScript diagnostics compact in the chat or handoff. Use the full output locally to fix the app, but report grouped root causes and only a few representative diagnostics instead of pasting the entire tsc output.
  • Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.
  • Search touched files for row[0], row[1], row.orderedAt, row.orderDate, as unknown as, DisplayRow, <select, margin, rate, score, percent, %, * 100, and .toFixed; fix positional rows, result-key guesses, entity <select> filters, and unsupported business-field interpretations.
  • Verify every date preset bar includes Custom last unless explicitly omitted, every visible date filter affects the current page, and no page shows duplicate date filters for one scope.
  • Verify data_app.yaml points at the built bundle path and that the bundle path is tracked by git.
  • For every visible filter, verify "All" maps to no filter, selected values come from runtime query results, and each non-All option changes every card it claims to affect.

Common Mistakes

  • Creating or searching for Metabase content during app building.
  • Writing the query object at the hook call instead of exporting it from queries/ with defineQuery, or the action at useAction instead of from actions/ with defineAction. Both are compile errors now; the fix is the directory, not a cast.
  • Wrapping the inline object in defineQuery(...) or defineAction(...) at the call site. It compiles, but sync-resources never sees it, so it is refused in production.
  • Putting definitions under src/queries/ or src/actions/, where sync-resources never looks.
  • Importing older hooks instead of useMetabaseQuery.
  • Copying raw numeric IDs into constants instead of using generated schema objects.
  • Inventing ad hoc measure objects such as { name: "count" } or { name: "sum", field: fieldId }.
  • Passing raw strings for table fields.
  • Adding lookup helpers instead of using keyed generated schema objects.
  • Inventing SDK component prop names instead of using query for generated table queries.
  • Mixing fields, segments, or measures from unrelated tables.
  • Passing a segment or measure to the dynamic second argument, where only result columns resolve.
  • Adding a filter UI that sends empty values instead of omitting the filter.
  • Hardcoding categorical filter values instead of querying the runtime values from Metabase.
  • Displaying entity names but filtering by those names when a stable ID is available.
  • Applying a dashboard-level filter to only one KPI while related charts and tables ignore it.
  • Showing a global Date Range plus a page-specific Snapshot Date where one date filter has no effect.
  • Letting a KPI and its detail table use different date or category filters without explaining the difference.
  • Rendering Margin/Rate/Score/Health with invented %, stars, colors, or thresholds.
  • Shipping a date preset bar with no Custom range option, or Custom before All time.
  • Charting opaque IDs such as franchise_id when a user-facing name is available.
  • Rendering an entity filter in a plain <select>, even if the current runtime option list is short.
  • Reaching for native <input type="date"> or any date picker dependency (react-datepicker, react-day-picker, a UI suite's picker) for a date range instead of DateRangePopover, and shipping browser-controlled mm/dd/yyyy placeholders or unthemed calendar popovers.
  • Labelling a date trigger with new Date("YYYY-MM-DD").toLocaleDateString() instead of useDateFormatter(), so the label is a day early for users west of Greenwich.
  • Assuming filter(...) fully validates value types.
  • Letting a null bucket become the latest time-series point.
  • Hardcoding business values, labels, timestamps, or rankings.
  • Creating chart-ready arrays by hand instead of deriving them from queried data.rows.
  • Casting typed SDK rows to generic tuple rows such as [string, number].
  • Reading generated object property names such as row.orderedAt when Metabase returns column names such as ordered_at.
  • Rendering fields that are not present in the schema or returned query result.
  • Rendering No data while the SDK is still authenticating or loading.
  • Creating nested MetabaseProvider instances instead of sharing one provider at the app boundary.
Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

NOASSERTION

Source path

skills/metabase-data-app-semantic-layer

Default branch

master

Latest commit

fc5cf5c

Tree SHA

27486b9