# Load rows from a REST API

> Connect the server-side row model to a REST endpoint with fetch, translate each block request into a query string and cancel stale requests with AbortSignal.

With the server-side row model the grid asks your server for one block of rows at a time as the user scrolls. Sorting, filtering and grouping happen on the server, so the browser only holds the blocks it has loaded. This recipe wires it to a REST endpoint such as `GET /api/orders?offset=0&limit=100&sort=-total`.

> **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.

**Live demo: Server-side row model** (runs on the HTML version of this page). Source of `demos/recipe-grid-server-side.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { ServerSideRowModelModule, createInMemoryDatasource, type ServerSideApi } from '@birchui/grid-pro';
import { button, docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, type Order } from './_shared';

export const meta = { title: 'Server-side row model', height: 460 };

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, filter: 'text' },
  { field: 'region', header: 'Region', width: 140, filter: 'text' },
  { field: 'status', header: 'Status', width: 120, filter: 'text' },
  { field: 'quantity', header: 'Qty', type: 'number', width: 90, filter: 'number' },
  { field: 'unitPrice', header: 'Unit price', type: 'number', width: 110, format: formatCurrency },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const datasource = createInMemoryDatasource(makeOrders(20_000, 17), { latencyMs: 350, reportRowCount: true });
  let requests = 0;
  const grid = createGrid<Order>(body, {
    columns,
    getRowId: (order) => order.id,
    modules: [ServerSideRowModelModule],
    rowModel: 'server',
    serverSide: {
      blockSize: 100,
      maxBlocksInCache: 20,
      debounceMs: 100,
      datasource: {
        getRows(request) {
          requests++;
          status.textContent = `Request ${requests}: rows ${request.startRow}-${request.endRow}, ${request.sort.length} sort keys, ${Object.keys(request.filterModel).length} filters.`;
          return datasource.getRows(request);
        },
      },
    },
    floatingFilters: true,
    theme: docsTheme(),
    ariaLabel: 'Orders loaded from a server',
  });
  const server = grid as typeof grid & ServerSideApi;
  toolbar.append(
    'Each block of 100 rows is fetched with 350 ms of simulated latency.',
    button('Refresh', () => server.refreshServerSide({ purge: true })),
  );
  const offError = server.onServerSideError((event) => {
    status.textContent = `Rows ${event.startRow}-${event.endRow} failed to load.`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    offError();
    stopTheme();
    grid.destroy();
  };
}
```

The demo answers requests with `createInMemoryDatasource()` and simulated latency, so it runs without a backend.

## 1. Turn a request into a query string

Each call to `getRows` receives a `ServerSideRequest`:

**`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` |  |

Map it to the parameters your API understands:

```ts title="orders-query.ts"
import type { FilterModel, ServerSideRequest } from '@birchui/core';

function filterParam(colId: string, model: FilterModel): [string, string][] {
  switch (model.type) {
    case 'text':
      return model.value ? [[`${colId}[${model.op}]`, model.value]] : [];
    case 'number':
      return model.value === undefined ? [] : [[`${colId}[${model.op}]`, String(model.value)]];
    case 'set':
      return [[`${colId}[in]`, model.values.map(String).join(',')]];
    case 'boolean':
      return [[colId, String(model.value)]];
    default:
      return [];
  }
}

export function toQueryString(request: ServerSideRequest): string {
  const params = new URLSearchParams({
    offset: String(request.startRow),
    limit: String(request.endRow - request.startRow),
  });
  if (request.sort.length > 0) {
    params.set('sort', request.sort.map(({ colId, dir }) => (dir === 'desc' ? `-${colId}` : colId)).join(','));
  }
  if (request.quickFilter) params.set('q', request.quickFilter);
  for (const [colId, model] of Object.entries(request.filterModel)) {
    for (const [key, value] of filterParam(colId, model)) params.append(key, value);
  }
  return params.toString();
}
```

Extend `filterParam` for the filter types your columns use: date filters, `between` ranges with `valueTo`, and `combined` filters with nested `conditions`.

## 2. Write the datasource

```ts title="orders-datasource.ts"
import type { ServerSideDatasource } from '@birchui/core';
import { toQueryString } from './orders-query';
import type { Order } from './orders';

interface OrdersPage {
  items: Order[];
  total: number;
}

export const ordersDatasource: ServerSideDatasource<Order> = {
  async getRows(request) {
    const response = await fetch(`/api/orders?${toQueryString(request)}`, {
      headers: { Accept: 'application/json' },
      signal: request.signal,
    });
    if (!response.ok) throw new Error(`GET /api/orders failed with status ${response.status}`);
    const page = (await response.json()) as OrdersPage;
    return { rows: page.items, rowCount: page.total };
  },
};
```

Return `rowCount` when the server knows the total; the scrollbar is then exact from the first block. If it does not, return only `rows`: a block shorter than the block size tells the grid it has reached the end. `lastRow` is accepted as an alias of `rowCount`.

## 3. Create the grid

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

const grid = createGrid<Order>(document.querySelector<HTMLElement>('#orders')!, {
  modules: [ServerSideRowModelModule],
  rowModel: 'server',
  serverSide: {
    datasource: ordersDatasource,
    blockSize: 100,
    maxBlocksInCache: 50,
    debounceMs: 80,
  },
  getRowId: (order) => order.id,
  floatingFilters: true,
  columns: [
    { field: 'id', header: 'Order', width: 120 },
    { field: 'customer', header: 'Customer', flex: 1, filter: 'text' },
    { field: 'status', header: 'Status', filter: 'set', options: ['Pending', 'Shipped', 'Delivered'] },
    { field: 'total', header: 'Total', type: 'number', filter: 'number' },
  ],
});

const server = grid as typeof grid & ServerSideApi;

server.onServerSideError(({ error, startRow, endRow, retry }) => {
  console.warn(`Orders ${startRow}-${endRow} failed to load`, error);
  setTimeout(retry, 2000);
});

document.querySelector('#refresh')!.addEventListener('click', () => server.refreshServerSide({ purge: true }));
```

**`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` |  |

## How it works

- The grid requests the blocks that cover the visible rows. `blockSize` defaults to 100 rows. With `maxBlocksInCache` set, blocks beyond that limit are dropped and fetched again when the user scrolls back.
- A change to the sort, filter model or quick filter discards the cached blocks and aborts their requests through `signal`. `debounceMs` waits for typing in a floating filter to settle before requesting.
- When `getRows` rejects, the block shows a load error. Listeners registered with `onServerSideError` receive the error and a `retry()` function; without a listener the error is logged with `console.error`.
- `refreshServerSide()` reloads the loaded blocks; `{ purge: true }` also clears them first.

## Pitfalls

- **Pass `signal` to `fetch`.** Without it, a slow response for an old sort can still arrive and waste bandwidth. The grid ignores stale responses either way, but the server keeps working on them.
- **Sort and filter on the server.** The grid sends the models and shows rows in the order you return them. A server that ignores `sort` makes the header arrows lie.
- **Ids must be unique across blocks.** Set `getRowId` to a database key so selection survives reloads.
- **Pivot mode is not available** with the server-side row model and is ignored with a warning.

## Related

- [Load rows from GraphQL](https://docs.birchui.com/recipes/grid-server-side-graphql.md) uses the same datasource contract.
- [Filter models](https://docs.birchui.com/grid/filtering.md#filter-models) lists every shape `filterModel` can hold.
- [Server-side sorting](https://docs.birchui.com/grid/sorting.md#server-side-sorting) and [server-side paging](https://docs.birchui.com/grid/pagination.md#server-side-paging).
- [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) for module registration and license keys.
