# Building with Next.js

In this guide, you build a product catalog with the Next.js App Router. The server renders the page with the filters in the URL, so a shared link opens the filtered list. The browser then loads its own dcupl instance and filters without asking the server, and every change is written back to the URL's query string.

**Time required:** 20 minutes

**What you will build:** a catalog page with a search field and category checkboxes with facet counts, whose filters live in `searchParams`.

## Prerequisites

- Completed the [Build your first dcupl application](/learn/tutorials/first-app) tutorial
- A supported Node.js version, see [Compatibility](/sdk/compatibility#nodejs) (`node -v` to check)
- Basic React and App Router knowledge (Server and Client Components)

## How the pieces fit

| Where            | What runs                                                                                             |
| ---------------- | ----------------------------------------------------------------------------------------------------- |
| Server process   | One dcupl instance, created on the first request and shared by every request after it                 |
| Page (server)    | Reads the filters from `searchParams`, queries a list, renders the result and destroys the list       |
| Browser tab      | One dcupl instance, loaded after the server-rendered page shows                                       |
| Catalog (client) | Shows the server's result until its instance is ready, then filters in the browser and writes the URL |

Both sides use the same three modules: the data, the instance and the filter functions. So the server and the browser agree on what a URL means.

## Step 1: create a Next.js project

```bash filename="terminal"
npx create-next-app@latest dcupl-next --ts --app --src-dir --eslint --no-tailwind --import-alias "@/*" --use-npm --yes
cd dcupl-next
npm install @dcupl/core@2 @dcupl/common@2
```

New projects turn on Cache Components (`cacheComponents: true` in `next.config.ts`). The page in Step 5 works with it on or off.

## Step 2: define the model and the data

The model and a few products live in one file. [Load from the Console](#load-from-the-console) shows how to load them from a Console project instead.

```typescript filename="src/lib/products.ts"
import type { ModelDefinition } from '@dcupl/common';

export type Product = {
  key: string;
  name: string;
  category: string;
  price: number;
};

export const productModel: ModelDefinition = {
  key: 'Product',
  properties: [
    { key: 'name', type: 'string' },
    { key: 'category', type: 'string' },
    { key: 'price', type: 'float' },
  ],
};

export const products: Product[] = [
  { key: 'p1', name: 'Wireless Headphones', category: 'Electronics', price: 299.99 },
  { key: 'p2', name: 'Mechanical Keyboard', category: 'Electronics', price: 149.99 },
  { key: 'p3', name: 'Running Shoes', category: 'Sports', price: 129.99 },
  { key: 'p4', name: 'Coffee Maker', category: 'Home', price: 89.99 },
  { key: 'p5', name: 'Yoga Mat', category: 'Sports', price: 39.99 },
  { key: 'p6', name: 'Smart Watch', category: 'Electronics', price: 249.99 },
  { key: 'p7', name: 'Desk Lamp', category: 'Home', price: 49.99 },
  { key: 'p8', name: 'Water Bottle', category: 'Sports', price: 24.99 },
];
```

## Step 3: one instance per process

`getDcupl()` keeps the promise of its first call in the module. On the server, that is one instance per server process, shared by every request: `init()` parses every model and data file, so an instance per request would be slow. In the browser, the same module gives each tab one instance.

```typescript filename="src/lib/dcupl.ts"
import { Dcupl } from '@dcupl/core';
import { productModel, products } from './products';

let instance: Promise<Dcupl> | null = null;

// One instance per server process, and one per browser tab
export function getDcupl(): Promise<Dcupl> {
  instance ??= (async () => {
    const dcupl = new Dcupl();
    dcupl.models.set(productModel);
    dcupl.data.set(products, { model: 'Product' });
    // init() resolves false instead of throwing: don't keep a failed instance
    if (!(await dcupl.init())) throw new Error('dcupl.init() failed');
    return dcupl;
  })().catch((error: unknown) => {
    instance = null; // the next call tries again
    throw error;
  });
  return instance;
}
```

A server instance keeps the data it loaded at startup. When the data changes while the server runs, reload it as shown under [Node.js server and SSR](/sdk/guides/deployment#nodejs-server-and-ssr).

## Step 4: filters as URL state

The filters are plain data: a search text and the ticked categories. These functions turn a URL into filters and back, apply the filters to a list and read the result as a serializable view that the server can hand to a Client Component:

```typescript filename="src/lib/filters.ts"
import type { DcuplList } from '@dcupl/core';
import type { Product } from './products';

export type Filters = { q: string; categories: string[] };

export type CatalogView = {
  items: Product[];
  total: number;
  categories: { value: string; size: number; selected: boolean }[];
};

const PAGE_SIZE = 24;

// ?q=lamp&category=Home&category=Sports
export function parseFilters(params: URLSearchParams): Filters {
  return {
    q: params.get('q')?.trim() ?? '',
    categories: params.getAll('category'),
  };
}

export function toSearch(filters: Filters): string {
  const params = new URLSearchParams();
  if (filters.q) params.set('q', filters.q);
  for (const category of filters.categories) params.append('category', category);
  const search = params.toString();
  return search ? `?${search}` : '';
}

// The page's searchParams prop, as URLSearchParams
export function toURLSearchParams(record: Record<string, string | string[] | undefined>): URLSearchParams {
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries(record)) {
    for (const entry of [value ?? []].flat()) params.append(key, entry);
  }
  return params;
}

const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');

export function applyFilters(list: DcuplList<Product>, filters: Filters): void {
  list.catalog.query.clear();
  if (filters.q) {
    list.catalog.query.addCondition({
      attribute: 'name',
      operator: 'find',
      value: `/${escapeRegex(filters.q)}/`,
      options: { regexFlags: 'i' },
    });
  }
  // conditions on the same attribute are combined with OR
  for (const category of filters.categories) {
    list.catalog.query.addCondition({ attribute: 'category', operator: 'eq', value: category });
  }
}

export function readView(list: DcuplList<Product>): CatalogView {
  return {
    items: list.catalog.query.items({ count: PAGE_SIZE }),
    total: list.catalog.fn.metadata().currentSize,
    categories: list.catalog.fn
      .facets({ attribute: 'category', excludeZeros: false, skipKeys: true })
      .map(({ value, size, selected }) => ({ value: String(value), size, selected })),
  };
}
```

- `applyFilters()` starts from `clear()`, so the list's query is always exactly what the URL says, whatever was applied before.
- A `find` value between slashes is a regular expression, so the search text is escaped first ([find](/sdk/api/query-operators#find)).
- `facets()` leaves out the `category` conditions when it counts, so each category shows how many products it would add ([Facets](/sdk/fn/facets)). `skipKeys: true` leaves out the item keys of each facet, which the page doesn't need to send.
- `metadata().currentSize` counts every match; `items({ count })` returns the first page of them.

## Step 5: render on the server

Replace `src/app/page.tsx`. The part that reads `searchParams` runs at request time, inside a `<Suspense>` boundary; with Cache Components on, everything outside it can be prerendered.

```tsx filename="src/app/page.tsx"
import { Suspense } from 'react';
import { connection } from 'next/server';
import { getDcupl } from '@/lib/dcupl';
import { applyFilters, parseFilters, readView, toURLSearchParams } from '@/lib/filters';
import type { Product } from '@/lib/products';
import { Catalog } from './catalog';

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

export default function Page({ searchParams }: { searchParams: SearchParams }) {
  return (
    <Suspense fallback={<p>Loading products…</p>}>
      <ServerCatalog searchParams={searchParams} />
    </Suspense>
  );
}

// Renders on the server, per request, with the filters in the URL
async function ServerCatalog({ searchParams }: { searchParams: SearchParams }) {
  await connection(); // the rest runs at request time only
  const filters = parseFilters(toURLSearchParams(await searchParams));
  const dcupl = await getDcupl();
  const list = dcupl.lists.create<Product>({ modelKey: 'Product' });
  try {
    applyFilters(list, filters);
    return <Catalog initialView={readView(list)} />;
  } finally {
    list.destroy(); // a list stays registered until it is destroyed
  }
}
```

`await connection()` tells Next.js not to prerender the rest of the component. Without it, the development server reports that it "encountered the unstable value `Math.random()` while prerendering": the SDK uses random values internally, for example for list keys.

The list is created and destroyed per request; the instance stays. For a one-off query without a list, use [`dcupl.query.execute()`](/sdk/api/dcupl#query).

## Step 6: filter in the browser

The Client Component starts with the server's view, so the first render in the browser matches the HTML and the page is usable before the browser has loaded any data. Once its own instance is ready, it applies the URL's filters to a browser list.

A filter change writes the URL with `window.history.replaceState()`. Next.js picks that up in `useSearchParams()` without a request to the server, and the component filters again in the browser:

```tsx filename="src/app/catalog.tsx"
'use client';

import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import type { DcuplList } from '@dcupl/core';
import { getDcupl } from '@/lib/dcupl';
import { applyFilters, parseFilters, readView, toSearch, type CatalogView, type Filters } from '@/lib/filters';
import type { Product } from '@/lib/products';

export function Catalog({ initialView }: { initialView: CatalogView }) {
  const searchParams = useSearchParams();
  const filters = useMemo(() => parseFilters(new URLSearchParams(searchParams.toString())), [searchParams]);
  const [list, setList] = useState<DcuplList<Product> | null>(null);

  // The browser's own instance, loaded after the server-rendered page shows
  useEffect(() => {
    let cancelled = false;
    let created: DcuplList<Product> | undefined;
    getDcupl().then((dcupl) => {
      if (cancelled) return;
      created = dcupl.lists.create<Product>({ modelKey: 'Product' });
      setList(created);
    });
    return () => {
      cancelled = true;
      created?.destroy();
    };
  }, []);

  // Until the instance is ready, show what the server rendered
  const view = useMemo(() => {
    if (!list) return initialView;
    applyFilters(list, filters);
    return readView(list);
  }, [list, filters, initialView]);

  // Writes the filters to the URL without a request to the server
  function setFilters(next: Filters) {
    window.history.replaceState(null, '', `${window.location.pathname}${toSearch(next)}`);
  }

  function toggleCategory(category: string) {
    const categories = filters.categories.includes(category)
      ? filters.categories.filter((c) => c !== category)
      : [...filters.categories, category];
    setFilters({ ...filters, categories });
  }

  return (
    <main>
      <input
        type="search"
        aria-label="Search products"
        placeholder="Search products"
        defaultValue={filters.q}
        onChange={(event) => setFilters({ ...filters, q: event.target.value.trim() })}
      />
      <fieldset>
        <legend>Category</legend>
        {view.categories.map((facet) => (
          <label key={facet.value}>
            <input type="checkbox" checked={facet.selected} onChange={() => toggleCategory(facet.value)} />
            {facet.value} ({facet.size})
          </label>
        ))}
      </fieldset>
      <p>{view.total} products</p>
      <ul>
        {view.items.map((product) => (
          <li key={product.key}>
            {product.name}: {product.price.toFixed(2)}
          </li>
        ))}
      </ul>
    </main>
  );
}
```

- `replaceState()` keeps one history entry for the page. Use `window.history.pushState()` instead if the back button should step through the filter changes.
- `router.push()` or `router.replace()` would also change the URL, but they render the page on the server again for every change. The browser instance makes that request unnecessary.
- The effect's cleanup destroys the browser list when the component unmounts. In development, React runs the effect twice; the `cancelled` flag keeps the first run from creating a list.

## Step 7: run it

```bash filename="terminal"
npm run dev
```

Open `http://localhost:3000/?category=Sports`: the server renders the three Sports products, with the **Sports** box ticked. Tick **Home**: the URL becomes `?category=Sports&category=Home` and five products show, without a request to the server. Type `la` and only the Desk Lamp is left; reload the page and the server renders the same result from the URL.

`npm run build` prerenders the page around the `<Suspense>` boundary and renders the catalog per request.

## Load from the Console

To load a Console project instead of the inline data, install the loader and replace `getDcupl()`:

```bash filename="terminal"
npm install @dcupl/loader@2
```

```typescript filename="src/lib/dcupl.ts"
import { Dcupl } from '@dcupl/core';
import { DcuplAppLoader } from '@dcupl/loader';

let instance: Promise<Dcupl> | null = null;

export function getDcupl(): Promise<Dcupl> {
  instance ??= (async () => {
    const dcupl = new Dcupl({
      config: {
        projectId: process.env.NEXT_PUBLIC_DCUPL_PROJECT_ID!,
        // NEXT_PUBLIC_ variables end up in the browser bundle: a read-only key only
        apiKey: process.env.NEXT_PUBLIC_DCUPL_API_KEY!,
      },
    });
    const loader = new DcuplAppLoader();
    dcupl.loaders.add(loader);
    await loader.config.fetch();
    await loader.process({ applicationKey: 'default' });
    if (!(await dcupl.init())) throw new Error('dcupl.init() failed');
    return dcupl;
  })().catch((error: unknown) => {
    instance = null;
    throw error;
  });
  return instance;
}
```

Put the two variables into `.env.local`, and change `modelKey`, the `Product` type and the filtered attributes to a model of your project. The browser needs the key too, so it is part of the bundle and anyone can read it; see [What the API key protects](/sdk/guides/deployment#what-the-api-key-protects). Keys that can write stay on the server, in variables without the `NEXT_PUBLIC_` prefix. [Load from the Console](/sdk/guides/load-from-console) covers versions and environments.

## Common issues

**The build fails with "uncached or runtime data during prerendering"**

With Cache Components on, a component that awaits `searchParams` must render inside a `<Suspense>` boundary, as `ServerCatalog` does in Step 5.

**Each filter change sends a request to the server**

The filters are written with `router.push()`, `router.replace()` or a `<Link>`. Those navigate, and the server renders the page again. Write the URL with `window.history.replaceState()` or `pushState()`.

**The page shows the server's result, then jumps**

The browser applies the same filters to the same data, so its first result matches the server's. If it differs, the two instances loaded different data: check that the server and the browser load the same project and version, and that the server instance has [reloaded the data](/sdk/guides/deployment#nodejs-server-and-ssr) since it was published.

## Next steps

- [Deployment](/sdk/guides/deployment) — Server instances, data refresh, API keys and the Content Security Policy
- [Building with React](/learn/tutorials/react-integration) — Hooks for a client-only React app
- [Facets](/sdk/fn/facets) — Counts per value for filter UIs
- [Load from the Console](/sdk/guides/load-from-console) — Load a Console project with the loader
