# Server-side row model

> Load rows in blocks from your server as the user scrolls, with sorting, filtering, grouping and aggregation done on the server, for results of any size.

When the rows live in your database, the server-side row model asks a datasource for one block of rows at a time as the user scrolls. The server sorts, filters, groups and aggregates, and the browser only holds the blocks it has loaded, so a result can have millions of rows.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> The server-side row model requires `ServerSideRowModelModule` from `@birchui/grid-pro`. It is not part of `AllProModules`; add it yourself. It adds about 7 KB minified and gzipped.

## Setting it up

Add the module, set `rowModel: 'server'`, and pass a datasource in `serverSide`:

```ts title="orders-grid.ts"
import { createGrid, type ServerSideDatasource } from '@birchui/core';
import { RowGroupingModule, ServerSideRowModelModule, type ServerSideApi } from '@birchui/grid-pro';

interface Order {
  id: string;
  customer: string;
  region: string;
  status: string;
  units: number;
  total: number;
}

const datasource: ServerSideDatasource<Order> = {
  async getRows({ signal, ...query }) {
    const response = await fetch('/api/orders/query', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(query),
      signal,
    });
    if (!response.ok) throw new Error(`Order query failed with status ${response.status}`);
    return response.json();
  },
};

const grid = createGrid<Order>(document.querySelector<HTMLElement>('#orders')!, {
  licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY,
  modules: [RowGroupingModule, ServerSideRowModelModule],
  rowModel: 'server',
  serverSide: { datasource, blockSize: 100, maxBlocksInCache: 50, debounceMs: 60 },
  getRowId: (order) => order.id,
  groupBy: ['region'],
  floatingFilters: true,
  columns: [
    { field: 'id', header: 'Order', pinned: 'left', width: 120 },
    { field: 'customer', filter: true, flex: 1 },
    { field: 'region', filter: true, options: ['Europe', 'North America', 'Asia Pacific', 'Latin America'] },
    { field: 'status', filter: true },
    { field: 'units', type: 'number', aggFunc: 'sum' },
    { field: 'total', type: 'number', aggFunc: 'sum', filter: true },
  ],
});

const server = grid as typeof grid & ServerSideApi;
```

Pass `signal` to `fetch`. When the sort or a filter changes, the grid aborts requests that are no longer needed.

**`ServerSideOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ServerSideOptions<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `datasource` | `ServerSideDatasource<TRow>` |  |
| `blockSize?` | `number` |  |
| `maxBlocksInCache?` | `number` |  |
| `debounceMs?` | `number` |  |
| `getChildCount?` | `(groupRow: RowData) => number \| undefined` |  |

## Requests

**`ServerSideRequest`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ServerSideRequest
```

| Property | Type | Description |
| --- | --- | --- |
| `startRow` | `number` |  |
| `endRow` | `number` |  |
| `sort` | `SortItem[]` |  |
| `filterModel` | `Record<string, FilterModel>` |  |
| `quickFilter` | `string` |  |
| `groupKeys` | `string[]` |  |
| `rowGroupCols` | `string[]` |  |
| `valueCols` | `ServerSideValueColumn[]` |  |
| `signal` | `AbortSignal` |  |

- `startRow` and `endRow` (exclusive) are relative to the level being loaded: the top level, or the children of one group.
- `sort`, `filterModel` and `quickFilter` are the grid's current values. Filters with `type: 'custom'` hold a function, so translate them into something your server understands before sending the request.
- `groupKeys` is empty for the top level and holds the path of the group being expanded, such as `['Europe']`. `rowGroupCols` lists the grouped column ids, and `valueCols` the columns with an `aggFunc`.

## Results

**`ServerSideResult`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ServerSideResult<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `rows` | `TRow[]` |  |
| `rowCount?` | `number` |  |
| `lastRow?` | `number` |  |

Resolve with `rows`, plus `rowCount` when you know the total. When you don't, the grid shows one block of loading rows after the last loaded one and keeps growing as the user scrolls. Send `lastRow` (the total) once you reach the end, or return a block shorter than requested, and the grid stops there. Reject the promise to report a failure.

### Groups

With `RowGroupingModule` and `groupBy`, a request with empty `groupKeys` returns one row per group, with the group value under the grouped column id and aggregates under the value column ids:

```json
{ "region": "Europe", "units": 1250002, "total": 261997500, "childCount": 250000 }
```

Expanding the group requests its children with `groupKeys: ['Europe']`. Pass `getChildCount: (groupRow) => groupRow.childCount` to show the count next to the label before the children load.

## Trying it without a server

`createInMemoryDatasource(rows, { latencyMs, reportRowCount })` answers requests the way a server would, from an array: it filters, sorts, groups and aggregates, and can add latency. Use it for prototypes, documentation and tests, and to check your own server against it.

```ts
import { createInMemoryDatasource } from '@birchui/grid-pro';

const datasource = createInMemoryDatasource(orders, { latencyMs: 120 });
```

**`InMemoryDatasourceOptions`** (interface from `@birchui/grid-pro`, full reference: https://docs.birchui.com/api/grid-pro.md)

```ts
interface InMemoryDatasourceOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `latencyMs?` | `number` |  |
| `reportRowCount?` | `boolean` |  |

## Refreshing, errors and cache state

**`ServerSideApi`** (interface from `@birchui/grid-pro`, full reference: https://docs.birchui.com/api/grid-pro.md)

```ts
interface ServerSideApi
```

| Property | Type | Description |
| --- | --- | --- |
| `refreshServerSide` | `(options?: ServerSideRefreshOptions) => void` |  |
| `getServerSideCacheState` | `() => ServerSideCacheState` |  |
| `onServerSideError` | `(listener: (event: ServerSideErrorEvent) => void) => () => void` |  |
| `isAllSelected` | `() => boolean` |  |

- `refreshServerSide()` reloads the loaded blocks in place and keeps their rows visible until the new data arrives. `refreshServerSide({ purge: true })` drops the cache and starts again.
- A failed block shows `Couldn't load rows 201–300.` with a **Retry** button; <kbd>Enter</kbd> on the row retries too. `onServerSideError(listener)` receives `{ error, startRow, endRow, groupKeys, retry }`. Without a listener, failures are reported with `console.error`.
- `getServerSideCacheState()` describes every level and block (`loading`, `loaded` or `failed`), which is useful for a status line or a test.

```ts
server.onServerSideError(({ error, startRow, endRow, retry }) => {
  toast.show(`Rows ${startRow + 1}–${endRow} could not be loaded`, { action: 'Retry', onAction: retry });
  console.warn(error);
});
```

## Behaviour

- **Loading rows** are data rows whose `data` is a frozen, empty placeholder, so row indexes, `aria-rowcount`, scrolling and keyboard navigation are correct for the whole result. `isServerSidePlaceholder(row)` recognises one. Column callbacks (`valueGetter`, `format`, `cell`, `cellClass`, `editable`) are never called for them. Their cells show a shimmer with `aria-busy`, which stops under `prefers-reduced-motion`.
- **Sorting and filtering** drop the cache, abort requests in flight and load again. The grid never sorts or filters rows in the browser.
- **Selection** covers loaded rows. `selectAll()` and the header checkbox select what is loaded, and `isAllSelected()` is `true` only when every row of the result is loaded and selected. To act on everything that matches, send the current sort and filters to your server.
- **`getRows()`** returns the loaded rows. The module manages the `rows` option.
- **Not available**: pivot mode and tree data are ignored with a warning, and CSV and Excel exports see only the loaded rows. Export from your server instead.

## Styling

The loading shimmer and error row use `--lq-pro-skeleton-bg`, `--lq-pro-skeleton-shine` and `--lq-pro-error-fg`, on top of the shared `--lq-*` tokens. See [Theming](https://docs.birchui.com/grid/theming.md).

## Related

- [Server-side data from a REST API](https://docs.birchui.com/recipes/grid-server-side-rest.md) and [from GraphQL](https://docs.birchui.com/recipes/grid-server-side-graphql.md)
- [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md) and [aggregation](https://docs.birchui.com/grid-pro/aggregation.md)
- [Virtualization](https://docs.birchui.com/grid/virtualization.md) for large client-side datasets
