# Homepage search bar

Source: https://help.ruuster.com/idx/recipe-search-bar

> A homepage search bar that suggests cities, neighborhoods, ZIP codes and schools as the visitor types, then hands off to your server-rendered search page.

A search bar for your homepage. As the visitor types, it suggests places (cities, neighborhoods, ZIP
codes, school areas and the places in your boards' states), and picking one goes to your
[search page](https://help.ruuster.com/idx/recipe-search-page) with that place's `where` object in
the URL. The search page then renders the results on your server. The bar runs in the browser and
asks your own listings route for suggestions, so the page carries no key.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/search-box-1440.png" alt="Location search box, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>The location box the search bar is built from.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/search-box-375.png" alt="Location search box, on a phone (375 px wide)" width="375" height="812" loading="lazy" decoding="async"><figcaption>The location box the search bar is built from.</figcaption></figure>

The markup is `static/html/search-box.html` in `@ruuster/idx-recipes`. The [HTML and CSS recipe](https://help.ruuster.com/idx/recipe-html-css) shows how to fill it and which stylesheet and script to load.

The bar suggests after three characters, waits 300 ms between keystrokes, and works with the
keyboard and screen readers: the arrow keys move through the suggestions and Enter picks one.

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| As the visitor types | `GET /v1/suggest`, through your listings route | your secret key, added on your server | an hour at Ruuster's edge |

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/suggest" \
  --data-urlencode q=Midt \
  --data-urlencode limit=8 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.suggest({
  q: "Midt",
  limit: 8,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/suggest",
    params={
        "q": "Midt",
        "limit": "8",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'q' => 'Midt',
    'limit' => '8',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/suggest' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

## Steps

1. In `.env.local`, set `IDX_SECRET_KEY` (your secret key). No other key is needed.
2. Add your listings route at `app/api/idx/[...path]/route.ts`, as below. It adds your secret
   key on your server and passes on only what a page may ask for.
3. Put the `SearchBox` on your homepage with `action="/search"` and `baseUrl="/api/idx"`, as
   below.
4. Build the [search page](https://help.ruuster.com/idx/recipe-search-page), which reads the `where`
   object from the URL.
5. Open `http://localhost:3000`, type three letters of a place and pick it.

On a site builder with no server of its own (WordPress, Squarespace, Webflow, Wix), use the
[plain HTML search box](https://help.ruuster.com/idx/recipe-html-css) with no key instead: [No key in
your pages](https://help.ruuster.com/idx/keys-and-domains) explains how the Listings API recognizes
your site's address.

## The code

The listings route:

```ts
// app/api/idx/[...path]/route.ts
import { createListingsRoute } from "@ruuster/idx/route";

// Reads IDX_SECRET_KEY from the server environment. Pages never see it.
export const GET = createListingsRoute({ basePath: "/api/idx" });
```

The homepage:

```tsx
// app/page.tsx: the search bar hands off to /search.
import { SearchBox } from "@ruuster/idx-recipes";

export const revalidate = 300;

export default function Home() {
  return (
    <main>
      <h1>Find your next home</h1>
      <SearchBox action="/search" baseUrl="/api/idx" placeholder="City, neighborhood, ZIP or school" />
    </main>
  );
}
```

## Forms and your CRM

The search bar carries no form. Leads come from the forms on your listing pages
([Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms)).

## Rules this page follows

**MUST**

- Point the search box at your listings route and keep the secret key on your server.
- Pass the picked row's `where` object to the search page unchanged.

**NEVER**

- Put any key in the page: not in a `NEXT_PUBLIC_` variable, a prop or any browser code.
- Build a `where` object from the visitor's text yourself.

## Test it

Open your homepage, press Tab until the search box has focus, type "Mid", press the down arrow and
Enter. The browser goes to `/search?where=…` and the results are in view source. In the browser's
network panel, the suggest request goes to `/api/idx/suggest` and carries no key. View the page
source and search for `idx_`: nothing is found.

## Build it with AI

```text
Read RUUSTER_IDX.md first and follow its MUST and NEVER rules. Ask me if it doesn't cover something.

Add a search bar to the homepage of my site that hands off to my search page, following <https://help.ruuster.com/idx/recipe-search-bar>. Use the SearchBox component with baseUrl="/api/idx" and action="/search", and add the route app/api/idx/[...path]/route.ts with `export const GET = createListingsRoute({ basePath: "/api/idx" });` if it is not there yet. It suggests places after three characters, and picking one goes to /search with the place's where object in the URL. The search page renders that search on the server with my secret key.

Use this environment variable: IDX_SECRET_KEY (server only). Never paste a secret key into a chat. No key goes in any page: my pages call my own /api/idx route, made with createListingsRoute from @ruuster/idx/route, which adds my secret key on the server (on a site with no server, the widgets call the API with no key from my approved website address).

When you are done, tell me how to test it with the keyboard only.
```

On a site without React, such as PHP, Python, Ruby on Rails, Go or plain HTML, [Build without React: HTML, CSS and JavaScript](https://help.ruuster.com/idx/recipe-html-css) gives you the same markup, the stylesheet and the script for every widget.
