---
title: "Add search to your app"
description: "Index a model, query it as the person searching, and get facets and highlights that never show a record they may not read."
section: "guides"
status: "Building for 0.4"
spec: "search"
canonical: "https://mainsdk.dev/docs/guides/add-search"
updated: "2026-10-28"
---

# Add search to your app

> Index a model, query it as the person searching, and get facets and highlights that never show a record they may not read.

Status: Building for 0.4 · Canonical: https://mainsdk.dev/docs/guides/add-search · Updated: 2026-10-28

You will index one model and add a search route. It takes about 15 minutes.

## You need

- A MainSDK app with a `db` model, here `posts`, and an `access` action that says who may read it.

## 1. Declare the index

```yaml title="main.yaml"
search:
  driver: db
  indexes:
    posts:
      model: posts
      access: posts.read
      fields:
        text: { search: true, weight: 2 }
        tags: { facet: true, filter: true }
```

The `db` driver needs no account. Move to `typesense` or `meilisearch` later by changing `driver` and adding the engine's `key` and `regions`.

## 2. Query as the searcher

```ts title="app/api/search/route.ts"
import { auth, search } from "mainsdk";

export async function GET(req: Request) {
  const session = await auth.require(req);
  const q = new URL(req.url).searchParams.get("q") ?? "";
  return Response.json(await search.query({ index: "posts", q, for: { type: "user", id: session.user }, highlight: true, limit: 10 }));
}
```

`for` is required, and a query without it fails with `MAIN-SEARCH-0003`. The tenant and access filters run inside the engine's query, so nothing is filtered after the fact.

## 3. Keep the index current

Writes to the `posts` model reach the index through the job outbox, never the request path. To rebuild an index, call `search.reindex("posts")`; it resumes after a crash. `search.status("posts")` shows what is pending or failed.

## Check that it works

- A post you can read appears in the results; one you cannot read does not.
- Stop the engine: the query fails with `MAIN-SEARCH-0004`, and index changes stay queued.

## Next

- [Search reference](https://mainsdk.dev/docs/interfaces/search)
- [Ground an AI answer in search results](https://mainsdk.dev/docs/interfaces/search)
