# Examples

> Ready-to-run examples you install with one command, and how the pieces fit together when you build a table by hand

Source: https://data-table.openstatus.dev/docs/examples · Docs index: https://data-table.openstatus.dev/llms.txt · Full docs: https://data-table.openstatus.dev/llms-full.txt

Each example is a block: one command installs a working route into your app, with every block it needs. The files are yours from then on. Change the columns, point the route at your data, or delete the folder when your own table is running.

| Block                         | Route           | Data source         | Live mode | Chart |
| ----------------------------- | --------------- | ------------------- | --------- | ----- |
| `data-table-example-infinite` | `/example`      | In-memory mock API  | No        | Yes   |
| `data-table-example-tinybird` | `/example/logs` | Tinybird datasource | Yes       | Yes   |

## In-memory

```bash
npx shadcn@latest add @data-table-filters/data-table-example-infinite
```

This installs `/example`: a table schema, a mock API route that filters, computes facets and cursor-paginates in memory with the same semantics as the database handlers, and the infinite table with URL state, the command palette, the timeline chart and the row sheet. No database, no environment variables. Start the dev server and open `/example`.

Starting from an empty folder, the [Quick Start](/docs/quick-start) creates the Next.js app and installs this example in one command.

When your rows live in a database, replace `app/example/api/route.ts` with a [Drizzle](/docs/drizzle-orm) or [Tinybird](/docs/tinybird) handler. The client does not change.

## Log viewer on Tinybird

```bash
npx shadcn@latest add @data-table-filters/data-table-example-tinybird
```

This installs `/example/logs`: the example table with live mode, the timeline chart, facets and the row sheet, on a route built with the [Tinybird handler](/docs/tinybird). It also installs the in-memory example at `/example`, whose schema and rows it shares.

Then, with the [Tinybird CLI](https://www.tinybird.co/docs) installed:

```bash
tb local start
```

```bash
(cd tinybird && tb deploy)
```

```bash
npx tsx app/example/logs/seed.ts --follow
```

The seed script appends 5,000 rows over the last week, then one new row a second until you stop it. That gives live mode something to follow. Start the dev server and open `/example/logs`.

Neither `TINYBIRD_URL` nor `TINYBIRD_TOKEN` is needed locally: the example defaults to Tinybird Local at `http://localhost:7181` and reads its admin token from there. For Tinybird Cloud, set both, in your shell or in `.env.local`:

```bash
export TINYBIRD_URL=https://api.tinybird.co   # or your region's API host
export TINYBIRD_TOKEN=p.ey...                 # a token that can read the datasource
```

`tb deploy` deploys the `tinybird` folder as your local workspace's project. If you already have a Tinybird project, copy `tinybird/datasources/logs.datasource` into it instead.

### What gets installed

| File                                    | Purpose                                                     |
| --------------------------------------- | ----------------------------------------------------------- |
| `lib/tinybird/*`                        | The handler, the query client, the SQL literals             |
| `components/data-table/data-table-live` | The Live button and the marker row                          |
| `hooks/use-live-mode.ts`                | Tracks when live mode was switched on                       |
| `app/example/logs/api/route.ts`         | The route: `createTinybirdHandler` and `timelineChart`      |
| `app/example/logs/tinybird.ts`          | URL, token, the query function, and the row → event mapping |
| `app/example/logs/seed.ts`              | Appends rows through the Events API                         |
| `app/example/logs/client.tsx`           | The table with live mode                                    |
| `app/example/logs/page.tsx`             | The page: parses the URL state and renders the client       |
| `app/example/logs/schema.ts`            | The URL state: the example's filters plus `live`            |
| `app/example/logs/query-options.ts`     | The query options for `/example/logs/api`                   |
| `tinybird/datasources/logs.datasource`  | The datasource the route reads                              |

To read your own datasource instead, change `DATASOURCE` in `app/example/logs/tinybird.ts` and `columnMapping` in `app/example/logs/api/route.ts`. If you keep the seed script, update `toEvent` to match. See [Tinybird](/docs/tinybird) for every option.

## Building one by hand

The examples are these four steps, filled in. Each step links to its guide page for details.

### 1. Define your table

Use `createTableSchema` to declare every column — display, filters, sorting, and row details — in one place. See [Table Schema](/docs/table-schema) for the full API.

```tsx
// table-schema.tsx
import {
  col,
  createTableSchema,
  type InferTableType,
} from "@/lib/table-schema";

export const tableSchema = createTableSchema({
  level: col.presets.logLevel(["error", "warn", "info", "debug"]),
  date: col.presets.timestamp().label("Date").size(200).sheet(),
  latency: col.presets
    .duration("ms")
    .label("Latency")
    .sortable()
    .size(110)
    .sheet(),
  status: col.presets.httpStatus().label("Status").size(60),
  method: col.presets.httpMethod(["GET", "POST", "DELETE"]).size(69),
  host: col.string().label("Host").size(125).sheet(),
});

export type ColumnSchema = InferTableType<typeof tableSchema.definition>;
```

### 2. Create the filter schema

Bridge the table schema to filter state with `generateFilterSchema`, then add non-column fields like sort and pagination. See [State Management](/docs/state-management) for details.

```tsx
// schema.ts
import { createSchema, field } from "@/lib/store/schema";
import { generateFilterSchema } from "@/lib/table-schema";

export const filterSchema = createSchema({
  ...generateFilterSchema(tableSchema.definition).definition,
  sort: field.sort(),
  live: field.boolean().default(false),
  size: field.number().default(40),
});

export type FilterState = typeof filterSchema._type;
```

### 3. Set up the API route

Create an API handler with `createDrizzleHandler` that implements three-pass filtering, faceted search, and cursor pagination. See [Drizzle ORM](/docs/drizzle-orm) and [Data Fetching](/docs/data-fetching) for the underlying concepts.

```tsx
// app/api/route.ts
import { createDrizzleHandler } from "@/lib/drizzle";

const handler = createDrizzleHandler({
  db,
  table: logs,
  schema: tableSchema.definition,
  columnMapping,
  cursorColumn: "date",
});

export async function GET(req: NextRequest) {
  const search = searchParamsCache.parse(
    Object.fromEntries(req.nextUrl.searchParams),
  );
  const result = await handler.execute(search);
  return Response.json(
    SuperJSON.stringify({
      data: result.data,
      meta: {
        totalRowCount: result.totalRowCount,
        filterRowCount: result.filterRowCount,
        facets: result.facets,
      },
      prevCursor: result.prevCursor,
      nextCursor: result.nextCursor,
    }),
  );
}
```

### 4. Render

Wire up `useInfiniteQuery` with `DataTableInfinite` and populate filter fields dynamically from server-side facet data. See [Components](/docs/ui-components) for all available props.

```tsx
// client.tsx
import { DataTableStoreProvider, useFilterState } from "@/lib/store";
import { useNuqsAdapter } from "@/lib/store/adapters/nuqs";
import {
  generateColumns,
  generateFilterFields,
  generateSheetFields,
} from "@/lib/table-schema";
import { useInfiniteQuery } from "@tanstack/react-query";

const columns = generateColumns<ColumnSchema>(tableSchema.definition);
const filterFields = generateFilterFields<ColumnSchema>(tableSchema.definition);
const sheetFields = generateSheetFields<ColumnSchema>(tableSchema.definition);

export function Client() {
  const adapter = useNuqsAdapter(filterSchema.definition, { id: "logs" });

  return (
    <DataTableStoreProvider adapter={adapter}>
      <DataTableContent />
    </DataTableStoreProvider>
  );
}

function DataTableContent() {
  const search = useFilterState<FilterState>();
  const { data, isFetching, fetchNextPage, hasNextPage } = useInfiniteQuery(
    dataOptions(search),
  );

  const flatData = React.useMemo(
    () => data?.pages?.flatMap((page) => page.data ?? []) ?? [],
    [data?.pages],
  );

  const { sort, live, size, ...filter } = search;
  const defaultColumnFilters = Object.entries(filter)
    .map(([key, value]) => ({ id: key, value }))
    .filter(
      ({ value }) => value != null && !(Array.isArray(value) && !value.length),
    );

  return (
    <DataTableInfinite
      columns={columns}
      data={flatData}
      defaultColumnFilters={defaultColumnFilters}
      defaultColumnSorting={sort ? [sort] : undefined}
      filterFields={filterFields}
      sheetFields={sheetFields}
      schema={filterSchema.definition}
      isFetching={isFetching}
      fetchNextPage={fetchNextPage}
      hasNextPage={hasNextPage}
      commandSlot={
        <DataTableFilterAICommand
          schema={filterSchema.definition}
          tableSchema={tableSchema.definition}
          api="/api/ai-filters"
          tableId="logs"
        />
      }
    />
  );
}
```

> The `commandSlot` above uses the AI-enhanced command palette. It handles both structured queries (`host:api`) and natural language (_"slow requests from eu"_) in the same input. See [AI Filters](/docs/ai-filters) for the full setup including the API route.

## Live demos

These routes on this site run the setups above:

| Route                  | Pagination      | Data Source           | Live Mode   | Chart       |
| ---------------------- | --------------- | --------------------- | ----------- | ----------- |
| [/auto](/auto)         | Infinite scroll | In-memory             | No          | No          |
| [/default](/default)   | Client-side     | In-memory             | No          | No          |
| [/infinite](/infinite) | Infinite scroll | Mock API              | Yes         | Yes         |
| [/drizzle](/drizzle)   | Infinite scroll | PostgreSQL            | Yes         | Yes         |
| [/light](/light)       | Infinite scroll | Tinybird              | Yes         | Yes         |
| [/headless](/headless) | Infinite scroll | Any manifest endpoint | If declared | If declared |
