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 or .
- 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 named export in the root-level directory, and every action a named export in the root-level directory, both beside . Create both directories before writing the first hook call; the template ships them, each with a README. The hooks enforce this at compile time: , , and 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 or as a definition and import it, never a cast.
- Never remove, edit, or copy a generated or , even if it appears unused. Preserve it during refactors; use 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 /MBQL objects in app code. Do not pass inline query objects like
{ type: "query", query: { "source-table": table.id } }
, raw clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, , or . 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 , generated , generated , generated metrics in , generated metric , , , , and helpers such as and . Do not use source: schema.metrics.<name>
; metrics are aggregation expressions, not query sources.
- Do not use existing saved questions as or sources. Typed schemas do not expose or support 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 ; plain selects are only for short closed enums explicitly provided by the user.
- Use 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 from the same entry produces its label. It ships with the SDK and needs no dependency and no CSS import. is the same calendar inline, for when the app already has a container. Do not install a date picker library for a range — not , , , or a UI suite's picker (, , , …). Do not use native either: its placeholder and calendar popover are browser-controlled, often show , and cannot be reliably themed.
- Never build a date label with — a date-only string parses as UTC and shows the previous day west of Greenwich. Use / from , 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; 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 — never 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 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 , , , , , , or . 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 or with /. Do not hardcode chart-ready arrays, sample data, demo values, or schema-shaped mock values.
- Render charts with /. 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 property as to or ; never pass the whole hook result as .
- are keyed objects, not tuple arrays. Never read / , and never silence this with
as unknown as [string, number][]
, , or another tuple cast. If TypeScript says property does not exist, it is catching a real bug. For typed , use literal keys such as or generated field names such as row[ordersTable.fields.createdAt.name]
. Use with or after explicitly narrowing a key; do not index typed rows with arbitrary values from .
- Do not cast query objects to
Parameters<typeof useMetabaseQuery>[0]
or to . 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 ; this can collapse overload inference. Pass raw filter state between components and build each query's inline with spreads.
- Keep runtime state out of the base query in . A clause whose value comes from a control — a selected plan, a date range, a search box — belongs in the second argument to /, not in the query. See "Static and dynamic query parts".
- Do not include in queries with and ; breakouts determine grouped result columns. Use 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 .
- 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:
- 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.
- 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.
- 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 tree.
include-metric-library=true
for the whole tree.
library-collections=<id-or-entity-id>[,<id-or-entity-id>]
for specific Data or metrics library subcollections.
- for readable models that have actions. When combined with , it includes models with actions for that database only.
- 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
when the app needs any saved action under
schema.models.<model>.actions
; it includes all readable models with executable actions, unless
scopes them to one database. Models without executable actions are omitted to keep generated schemas compact. It can be combined with
,
, or
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
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 as
and
(one file per repo, usually two levels up
from the app dir, not in the app dir). The command below
s that file so
the shell substitutes the values straight into
— you never read, extract,
or handle the credentials yourself.
Never ask the user to paste the API key into the chat, and never /
— it's git-ignored and may hold other secrets, so its
contents must stay out of the conversation.
it so the shell uses the
values without exposing them. If
or
is empty
or still set to the default
placeholder after sourcing, ask
the user to add real values themselves, then continue.
Source the credentials from the repo-root
and generate the scoped
schema. The example below exports table data from the Data library; replace its
query parameters with the scope chosen above:
bash
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
/
/
,
/
, 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
—
for
,
for
.
scans only those two directories, so a definition under
,
, or any other source directory is silently never synchronized. Discovery covers
,
,
,
,
,
,
, and
.
ts
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
run reconciles both. For a query it materializes the authored table query as a saved question and injects
. For an action it copies the action's parent model into the app collection, copies the action onto that copy, and injects
; 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:
ts
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,
,
, 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
/
returned, so an inline object, a
-typed object, a spread copy, and
schema.models.<model>.actions.<action>
all fail to compile. When
reports
Property 'definedWithDefineQuery' is missing
or
Property 'definedWithDefineAction' is missing
, the argument is not a definition: move it into
or
and import the export. Do not silence it with a cast or by wrapping the inline object in
at the call site, which compiles but leaves the query unsynchronized. Keep fixed permission-boundary filters, aggregations, and breakouts inside
— 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).
needs no generics: the definition types
's parameters and
.
Wire
with
"sync-resources": "embedding-sdk-react data-apps sync-resources"
and
"build": "npm run sync-resources && vite build"
, then run
after adding, changing, renaming, or removing any definition; run
directly only to inspect generated state before a build. It reads
and
from the repo-root
.
Inline generated IDs and
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
succeeds, every live definition carries a positive generated ID, and
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
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
, the hook call in the component.
ts
// 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,
});
tsx
// 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);
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
. The recipes below show the object passed to
; each one is an export in
, never an argument written at the hook.
Call each schema entry at most once per render tree. Multiple
calls on the same
(or same
+ 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
/
/
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: inside
- 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
or
.
Static and dynamic query parts
Both query hooks take an optional second argument: the clauses that change while the app runs.
ts
// 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
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
/
, 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:
ts
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
if you find it on a query object, or
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
:
ts
// 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:
ts
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
helpers:
ts
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
,
, and
. TypeScript only models the base helper key today. For custom KPI code that intentionally uses repeated same-kind aggregations, read through
or cast the row to
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
and the generated metric object in
:
ts
// 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
; prefer those related-table dimensions for readable labels instead of grouping by raw foreign key IDs:
ts
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:
ts
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
in
. Do not use metric dimensions as standalone table fields for unrelated
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
.
When table queries use
,
,
,
, or
, let
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
or
— is decided in the data-app setup skill (
Rendering a chart: Metabase first). Once it is: declare the query in
, resolve it with
useMetabaseQueryObject(TheQuery)
, then pass the result through the SDK question component's
prop.
supports generated table queries, including metric aggregations. Use
when custom React needs direct row data; use
when Metabase should render or manage the visualization. Do not pass generics to
; it returns
{ query, error, isLoading }
, not query result rows.
The examples under
Rendering With SDK Components use
for minimal loading and error handling. In a real app, render the app's existing loading or error UI there. Passing
is safe while
is
; do not pass the full
{ query, error, isLoading }
hook result as
.
When wrapping
in a reusable chart/card component, destructure and render
; do not read only
, 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:
tsx
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 export imported from and nothing else; an inline object is a compile error. Write no generics on the hooks.
- 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 property to .
- Do not use
as Parameters<typeof useMetabaseQuery>[0]
or 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
object. Start with
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
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
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
and
combinations. Build the query with
; do not call internal query resolution helpers, cast through
, 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
, check
node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts
for the
return type. Destructure the returned
and use that value in
; for configured cards, type the object with
. If TypeScript reports duplicate opaque
symbols, do not force a cast; update the SDK package before using
.
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
prop shape.
When
is needed, map typed rows into an explicit local view model using named properties before rendering:
ts
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
at runtime, use
with the matching column position, or narrow the key to a literal before indexing
.
Rendering With SDK Components
Chart only, without the toolbar:
tsx
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:
tsx
// 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.
ts
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
object literals such as
or
; use
. When ordering the same date field used by a date breakout, pass the same
to both
and
.
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
and
:
ts
// 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
object:
ts
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")],
});
is the unaggregated
defineQuery({ source: scorecardTable })
export in
; its source fields survive into the result, so the dynamic stage can order by them.
For metric queries, pass generated metric dimensions to
and
:
ts
filter(revenueMetric.dimensions.orders.status, "=", "paid");
breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" });
Filter operator rules:
- string: , , , , , , , , ,
- number: , , , , , , , ,
- date: , , , , , , , , ,
- boolean: , ,
Only date dimensions can use
. Non-date dimensions can be used as breakouts without
; numeric dimensions can use
.
Segments are already filters:
ts
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
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 .
- 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 , 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:
tsx
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],
);
above is what
<DateRangePopover value={customRange} onChange={setCustomRange}>
stores, so there is nothing to convert. When a fallback picker's state uses
, convert selected dates with a local
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 .
- Never treat as positional arrays. Do not use , , , or tuple casts for row objects.
- Inspect before mapping low-level , but do not use arbitrary strings to index typed .
- Runtime row objects are keyed by returned Metabase column names, usually such as or . Do not assume generated schema keys like or 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 . Use row[ordersTable.fields.orderedAt.name]
, , or metadata instead of guessing .
- Treat row values as nullable. Guard before calling number/string methods such as , , or string transforms.
- Use only for known positional shapes.
- Aggregation columns may be named , , or ; match metadata when needed.
- If a custom visualization needs several helper aggregations with the same output name, such as multiple calls, prefer separate single-aggregation queries so each typed row has the known key. If one multi-aggregation query is necessary, read by column position after checking ; do not depend on generated names like unless they are explicitly typed or narrowed in the app code.
- Grouped queries can include a breakout bucket. Render it as 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 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
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 , , , , , , and 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 .
Property 'definedWithDefineQuery' is missing
or Property 'definedWithDefineAction' is missing
means a hook received something other than a or export; move the object there and import it.
- Search touched files for , , and . The first argument must be an identifier imported from or ; a , a , a , 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 and sit beside , not under , and that every definition the app renders lives there.
- Run ; 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 output.
- Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.
- Search touched files for , , , , , , , , , , , , , and ; fix positional rows, result-key guesses, entity 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 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 with , or the action at instead of from with . Both are compile errors now; the fix is the directory, not a cast.
- Wrapping the inline object in or at the call site. It compiles, but never sees it, so it is refused in production.
- Putting definitions under or , where never looks.
- Importing older hooks instead of .
- Copying raw numeric IDs into constants instead of using generated schema objects.
- Inventing ad hoc measure objects such as 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 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 /// 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 when a user-facing name is available.
- Rendering an entity filter in a plain , even if the current runtime option list is short.
- Reaching for native or any date picker dependency (, , a UI suite's picker) for a date range instead of , and shipping browser-controlled placeholders or unthemed calendar popovers.
- Labelling a date trigger with
new Date("YYYY-MM-DD").toLocaleDateString()
instead of , so the label is a day early for users west of Greenwich.
- Assuming fully validates value types.
- Letting a 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 .
- Casting typed SDK rows to generic tuple rows such as .
- Reading generated object property names such as when Metabase returns column names such as .
- Rendering fields that are not present in the schema or returned query result.
- Rendering while the SDK is still authenticating or loading.
- Creating nested instances instead of sharing one provider at the app boundary.