elements
Start Docs Blog Demos UI Pricing
Elements Manual
  • Getting Started
  • CLI
  • Build
  • Browser
  • Packages
  • TypeScript
  • Elements HTML
  • Assets
  • RPC
  • Router
  • Session
  • Database
  • Migrations
  • LiveTable
  • Channel
  • Jobs
  • Email
  • Payments
  • JSON
  • Async
  • Style
  • UI
  • JSOC
  • Config
  • Tests
  • Logs
  • Deploy
  • Editors
  • Recipes
    • Todo App
    • Todo App: Markup and Styles
    • Authentication
    • Form Validation
    • Signup with Email Confirmation
    • Signup Wizard
    • Admin Roles
    • File Upload
    • Serving Assets From the Database
    • Live Comments
    • Likes / Votes Toggle
    • Shared Lists
    • Team-Partitioned Table
    • Chat Rooms
    • Typing Indicator
    • Grouped Feed Without Flicker
    • Unread Counts
    • Room Presence
    • Collaborative Canvas
    • Infinite Scroll Feed
    • Bidirectional Partition
    • Search and Filter
    • Admin Table
    • Markdown Blog
    • Public and Admin Views
    • Cron Cache
    • Live Dashboard
    • Live Updates From Any Write
    • Marketing Page
    • Status Indicators
    • Markdown Editor
    • Time Ago
  • Licenses
  • Issues
  • Changelog
Manual / Recipes/ Search and Filter

Search and Filter

elements man recipes/search-filter

On This Page

  • Migration
  • Page setup
  • Routes
  • Notes

A product search page with a text query plus a multi-select category filter. As the user types or toggles a checkbox, a debounced @rpc runs server-side and returns the matching rows. The page state is one SearchQuery object bound to the inputs; the result list reassigns on every RPC return.

Filtering rows the page already holds is a different job with a different primitive. A LiveView has filter: todos.filter(predicate) returns the matching rows as an array, and an e:for over it renders again when the table changes. So tabs like All / Active / Done are one predicate in the e:for, with no RPC and no CSS hiding. That pattern is in elements man livetable, under "Reading rows from a LiveView", and worked in elements man recipes/todo-app.

This recipe has no LiveTable because it searches rows the browser never loads. Each query returns the rows that match at the moment it runs, and the results aren't shared across browsers. So the recipe uses an @rpc and a reactive form.

Migration

Terminal
elements create migration 'add products' -tables=products
app/migrations/<timestamp>-add-products.migration.sql
-- add products -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create type productCategory as enum ('books', 'movies', 'music'); create table products ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), name text not null, category productCategory not null, priceCents integer not null ); create index productsCategoryIdx on products (category); create trigger productsTouchUpdatedAt before update on products for each row execute function touchUpdatedAt();

productsCategoryIdx backs the category filter. The productCategory Postgres enum restricts the column to 'books', 'movies', and 'music'; the database rejects any other value at insert or update time. To add a category later, run alter type productCategory add value '<name>' in a follow-up migration.

Page setup

Terminal
elements create page search

The product types, the available category set, and the search RPC are used only by the /search page, so they are declared in the page's template.ehtml. The route imports them from there, runs the empty-query search, and passes the initial result set to the template; the template debounces input events into one RPC call per pause.

app/pages/search/template.ehtml, above the markup:

app/pages/search/template.ehtml
import "./style.css"; import { sql } from "@elements/app"; import { Input } from "@elements/ui/input"; import { Checkbox, CheckboxGroup } from "@elements/ui/checkbox"; import { FieldSet, FieldLegend } from "@elements/ui/field"; import { Label } from "@elements/ui/label"; import { Table, TableHead, TableCell } from "@elements/ui/table"; import { Badge } from "@elements/ui/badge"; import { Empty } from "@elements/ui/empty"; export type ProductCategory = "books" | "movies" | "music"; export interface Product { id: string; name: string; category: ProductCategory; priceCents: number; } export interface SearchQuery { text: string; categories: ProductCategory[]; } export const CATEGORIES: ProductCategory[] = ["books", "movies", "music"]; /** @rpc */ export function searchProducts(query: SearchQuery): Product[] { let pattern = `%${query.text.trim()}%`; if (query.categories.length > 0) { return sql<Product>(` select id, name, category, priceCents from products where name ilike ${pattern} and category = any(${query.categories}) order by name asc limit 50 `).all(); } return sql<Product>(` select id, name, category, priceCents from products where name ilike ${pattern} order by name asc limit 50 `).all(); }

pattern defaults to '%%' when the user types nothing, which matches every name. When no category is checked, the function runs the second query, which has no any clause. Postgres treats category = any(empty array) as always false, so the first query would return no rows for an empty filter.

ProductCategory mirrors the Postgres enum values; the union type narrows Product.category and the CATEGORIES array. To drive the filter options from the database, load them with a select distinct category from products query or from a dedicated categories table; see "Categories from the database" below.

app/pages/search/index.ts
import { Request, Response } from "@elements/app"; import search, { searchProducts, CATEGORIES } from "./template"; export default function route(req: Request, res: Response) { let initial = searchProducts({ text: "", categories: [], }); return new search({ initial, categories: CATEGORIES, }); }

The route runs the search with empty filters and passes the first 50 products as initial. The page server-renders with results already visible, no fetching spinner on mount.

The rest of app/pages/search/template.ehtml, under the code above:

app/pages/search/template.ehtml
let debounceTimer: ReturnType<typeof setTimeout> | null = null; function onChange(form: SearchQuery, results: { value: Product[] }) { if (debounceTimer !== null) { clearTimeout(debounceTimer); } debounceTimer = setTimeout(() => { results.value = searchProducts({ text: form.text, categories: form.categories.slice(), }); }, 300); } <html class="page-search" ( initial: Product[], categories: ProductCategory[], private form: SearchQuery = { text: "", categories: [], }, private results: { value: Product[] } = { value: initial }, )> <main class="page-shell"> <h1>products</h1> <form class="filters stack"> <Input type="search" value={form.text} placeholder="search by name" attrs={{ "aria-label": "search by name" }} oninput={() => onChange(form, results)} /> <FieldSet> <FieldLegend>category</FieldLegend> <CheckboxGroup value={form.categories} onValueChange={() => onChange(form, results)}> <Label e:for={cat of categories}><Checkbox value={cat} /> {cat}</Label> </CheckboxGroup> </FieldSet> </form> <Table label="products"> <table> <thead> <tr> <TableHead>name</TableHead> <TableHead>category</TableHead> <TableHead align="end">price</TableHead> </tr> </thead> <tbody> <tr e:for={p of results.value}> <TableCell>{p.name}</TableCell> <TableCell><Badge variant="secondary">{p.category}</Badge></TableCell> <TableCell align="end">${(p.priceCents / 100).toFixed(2)}</TableCell> </tr> </tbody> </table> </Table> <Empty e:if={results.value.length === 0} title="no matches" /> </main> </html>

The Input binds form.text with value. The CheckboxGroup binds form.categories: the checked boxes' values are the array, and a press writes the new set back. Both call onChange, which debounces a single RPC call across them. The results are a Table, the category a Badge, and Empty renders below the table when nothing matches.

The debounce timer is a module-level variable, so it keeps its value between events and is not template state. clearTimeout cancels the pending call when a new event arrives within 300 ms, so the page calls the RPC function once per pause in typing, not once per keystroke.

form.categories.slice() sends a copy of the array, so a checkbox toggled while the RPC call is in progress cannot change the array that call was given.

Routes

Register the page in index.ts:

index.ts
import search from "#app/pages/search"; // ... app.route("/search", search);

Notes

  • Debounce on the browser. The 300 ms gate sends one RPC call per pause. For a public search endpoint, add request limiting at the app level.
  • Server-side initial render. Running the empty-query search inside the route handler means the first paint shows results. The page isn't a blank state that fills in via RPC on mount.
  • Pagination. This recipe returns the first 50 matches. To page through longer result sets, use a keyset cursor as elements man recipes infinite-scroll-feed does: pass the last row's name and id to the RPC, add and (name, id) > (${lastName}, ${lastId}), order by name, id, and call for the next page from an intersection-observer sentinel.
  • Sort options. Add sort: "name" | "price-asc" | "price-desc" to SearchQuery and switch the order by clause inside the rpc. The template renders a NativeSelect bound to form.sort next to the checkboxes; the same onChange debounce wraps it.
  • Categories from the database. Replace the hardcoded CATEGORIES constant with a route-side load: let categories = sql<{ category: ProductCategory }>(\select distinct category from products order by category`).all().map(r => r.category);. Pass the result to the template alongside initial`.
  • Full-text search. ilike '%query%' matches substrings. For language-aware search, replace the where name ilike ${pattern} clause with a tsvector column (alter table products add column searchVector tsvector generated always as (to_tsvector('english', name)) stored), a GIN index (create index productsSearchIdx on products using gin (searchVector)), and where searchVector @@ to_tsquery('english', ${tsquery}). A tsvector search adds stemming, multi-word AND/OR queries, and rank-ordered results.
Prev Bidirectional PartitionNext Admin Table
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026