# Birch UI Grid in the Next.js App Router

> Render the grid from a Client Component in the Next.js App Router, load data in a Server Component, lazy-load Grid Pro and pass the license key from an environment variable.

In the App Router, pages are Server Components by default and the grid needs the browser. The pattern is simple: fetch data on the server, pass plain data to a Client Component, and create the grid there. The `examples/nextjs-app-router-grid` project in the Birch UI repository follows this recipe.

## 1. Install

```sh
npm install @birchui/core @birchui/react
```

## 2. Load data in a Server Component

```tsx title="app/orders/page.tsx"
import { OrdersGrid } from './orders-grid';
import { listOrders } from '@/lib/orders';

export default async function OrdersPage() {
  const orders = await listOrders({ status: 'open' });
  return (
    <main>
      <h1>Open orders</h1>
      <OrdersGrid orders={orders} />
    </main>
  );
}
```

Only serializable data crosses into the Client Component, so pass rows, not column definitions.

## 3. Render the grid in a Client Component

```tsx title="app/orders/orders-grid.tsx"
'use client';

import { useRef, useState } from 'react';
import { BirchGrid } from '@birchui/react';
import type { ColumnDef, GridApi } from '@birchui/core';
import type { Order } from '@/lib/orders';

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110, pinned: 'left' },
  { field: 'customer', header: 'Customer', flex: 1, minWidth: 180, filter: 'text' },
  { field: 'region', header: 'Region', filter: 'set' },
  { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' },
  { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) },
];

const getRowId = (order: Order) => order.id;

export function OrdersGrid({ orders }: { orders: Order[] }) {
  const grid = useRef<GridApi<Order>>(null);
  const [search, setSearch] = useState('');

  return (
    <>
      <input type="search" aria-label="Search orders" value={search} onChange={(event) => setSearch(event.target.value)} />
      <button type="button" onClick={() => grid.current?.downloadCsv({ fileName: 'orders.csv' })}>
        Export CSV
      </button>
      <BirchGrid<Order>
        ref={grid}
        style={{ height: 'calc(100vh - 200px)' }}
        columns={columns}
        rows={orders}
        getRowId={getRowId}
        quickFilter={search}
        floatingFilters
        theme="auto"
        licenseKey={process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY}
      />
    </>
  );
}
```

During server rendering `BirchGrid` outputs its empty container; the grid is created after hydration. Give it a height in CSS or `style`, so the space is reserved and the page does not shift.

Keep `columns` and callbacks such as `getRowId` at module level or memoized. A new array on every render is treated as a column change.

## 4. The license key

Next.js inlines variables prefixed with `NEXT_PUBLIC_` into the client bundle at build time:

```sh title=".env.local"
NEXT_PUBLIC_BIRCHUI_LICENSE_KEY=LQ1.your-key-here
```

The core grid is MIT licensed and ignores the key; wiring it now means Grid Pro modules need no further setup. Birch UI keys are verified offline and are meant to ship in client code, but keep real keys out of the repository. To set the key once for every widget instead of per grid, call `setLicenseKey()` from `@birchui/license` at module level in a `'use client'` provider that your root layout renders.

## 5. Lazy-load Grid Pro

Grid Pro adds weight that a page may not need until the user opens a report. Load the module and the component with `next/dynamic`:

```tsx title="app/reports/revenue-grid.tsx"
'use client';

import { BirchGrid } from '@birchui/react';
import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro';
import type { ColumnDef } from '@birchui/core';
import type { Sale } from '@/lib/sales';

const modules = [RowGroupingModule, AggregationModule];

const columns: ColumnDef<Sale>[] = [
  { field: 'region', header: 'Region', rowGroup: true },
  { field: 'product', header: 'Product' },
  { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' },
];

export default function RevenueGrid({ sales }: { sales: Sale[] }) {
  return (
    <BirchGrid<Sale>
      style={{ height: 520 }}
      columns={columns}
      rows={sales}
      modules={modules}
      groupDefaultExpanded={1}
      licenseKey={process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY}
    />
  );
}
```

```tsx title="app/reports/revenue-panel.tsx"
'use client';

import dynamic from 'next/dynamic';
import type { Sale } from '@/lib/sales';

const RevenueGrid = dynamic(() => import('./revenue-grid'), {
  ssr: false,
  loading: () => <div style={{ height: 520 }} aria-busy="true" />,
});

export function RevenuePanel({ sales }: { sales: Sale[] }) {
  return <RevenueGrid sales={sales} />;
}
```

`ssr: false` is only allowed inside Client Components, which is why the dynamic import lives in `revenue-panel.tsx`. The grid itself does not need it, since it is safe to import on the server; it only keeps the Pro code out of the initial bundle.

## Pitfalls

- **`'use client'` is required** on the file that renders `BirchGrid`. Without it, React reports hooks used in a Server Component.
- **Functions cannot be props from the server.** Define columns, formatters and `getRowId` in the client file.
- **Strict Mode** mounts the grid twice in development. That is expected; the second instance is the one the ref points to.
- **Without a key on a public host**, Grid Pro features still work but show a small watermark.

## Related

- [React](https://docs.birchui.com/frameworks/react.md) and its [Next.js section](https://docs.birchui.com/frameworks/react.md#nextjs-and-server-rendering).
- [Licensing](https://docs.birchui.com/getting-started/licensing.md#activate-your-key).
- [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md).
