Static site

Add search to a static website without running a backend

Our walking club's website is a static site: a few Markdown files, built and hosted for free. The routes page was one long list of 613 walks, and members kept asking for a search box and a way to filter by region and difficulty. Nobody in the club runs servers. So we put the routes behind SearchAPI and called it straight from the page's JavaScript. That worked within an evening. Then we noticed that the key in the page also handed out our walk leaders' phone numbers.

613
walking routes behind a search box
57
lines of JavaScript, no library
0
servers run by the club
403
for a write with the key in the page

The site and the data

The club, its routes and its leaders are made up, but the files have the shape our real ones had: the committee kept a sheet of routes and a separate list of the walk leaders who look after them.

FileRowsWhat's in it
routes.csv613Name, region code, difficulty, distance, ascent, duration, dogs allowed, surface, description and the leader's id.
regions.csv21National parks and hill areas in England, Wales and Scotland.
leaders.csv43Each walk leader's name and phone number.
search.htmlThe finished search page. Set two constants at the top and open it.

Import the three files

Each file becomes one model with its own endpoint. Regions and leaders go first, because routes point to them. The screens are described in Data import.

  1. Create an API, then open Data Import and choose Create New Model + Mapping + Endpoint.
  2. Upload regions.csv. Mark region_code as the primary key, and name and country as Visible In Related Model.
  3. Upload leaders.csv. Mark leader_id as the primary key, and leader_name and leader_phone as Visible In Related Model, so that a route can show who to call.
  4. Upload routes.csv. Mark route_id as the primary key, make name and description searchable text fields, and difficulty and surface keyword fields for exact filters.
  5. Set region_code to object pointing to the regions model and rename it region; do the same with leader_id, pointing to leaders, renamed leader.
  6. Choose difficulty, dogs_allowed, surface and region.name as aggregation fields. The page's filter menus use their counts.

Result: none of the three imports took more than a second, and each route embeds its region and its leader with the fields marked visible. That checkbox on leader_phone is the mistake we come back to below.

Two keys, and only one goes in the page

A key in a static site isn't a secret. Anyone can open the page source and copy it. What matters is what the key is allowed to do, and SearchAPI grants keys per HTTP method, endpoint by endpoint.

We needed the second key earlier than we expected: a version can't be deployed while any of its endpoints has no key at all. See API keys for assigning keys to endpoints.

The whole page is plain HTML with one script and no library. This is the part that builds the request; every value is URL-encoded, including the JSON filter for the region:

const API = 'https://your-subdomain.searchapi.net/trails/v2/routes'
const READ_KEY = 'your-read-only-key'

function buildUrl() {
  const f = new FormData(form)
  const params = [['includes', 'route_id,name,difficulty,distance_km,duration_hours,region']]
  if (f.get('q')) params.push(['q', f.get('q')])
  if (f.get('region')) params.push(['region', JSON.stringify({ region_code: f.get('region') })])
  if (f.get('difficulty')) params.push(['difficulty', f.get('difficulty')])
  if (f.get('maxKm')) params.push(['distance_km[to]', f.get('maxKm')])
  if (f.get('dogs')) params.push(['dogs_allowed', 'true'])
  return API + '?' + params.map(([k, v]) => `${enc(k)}=${enc(v)}`).join('&')
}

const res = await fetch(buildUrl(), { headers: { 'X-API-KEY': READ_KEY } })

The search runs 250 ms after the last keystroke or filter change. After the first load, typing "waterfall" and then choosing Moderate, a 10 km maximum and "Dogs allowed" sent two requests, not one per key press. This is the second:

GET https://trails.searchapi.net/trails/v2/routes?includes=route_id%2Cname%2Cdifficulty%2Cdistance_km%2Cduration_hours%2Cregion&q=waterfall&difficulty=Moderate&distance_km%5Bto%5D=10&dogs_allowed=true
X-API-KEY: your-read-only-key
"pagination": { "start": 0, "limit": 20, "count": 20, "total": 21, "nextSearchAfter": [1, "R-1544"] },
"results": [
  {
    "route_id": "R-1082",
    "name": "Waterfall Trail",
    "difficulty": "Moderate",
    "distance_km": 8.52,
    "duration_hours": 2.75,
    "region": { "region_code": "RG-09", "name": "Cotswolds", "country": "England" },
    "_score": 2
  },
  …
]

Results are written into the page with textContent, never innerHTML, so a route description can't inject markup into the site.

Counts in the filter menus

The Region and Difficulty filters on the page are <select> menus. The script rebuilds their options from the aggregations in each search response, so every option shows how many routes it would leave, for example "Lake District (3)". For the request above:

"aggregations": {
  "region_name": {
    "buckets": [
      { "key": "Lake District|RG-02", "doc_count": 3 },
      { "key": "South Downs|RG-06", "doc_count": 3 },
      { "key": "Cotswolds|RG-09", "doc_count": 2 },
      …
    ]
  },
  "dogs_allowed": {
    "buckets": [ { "key": 1, "key_as_string": "true", "doc_count": 21 }, … ]
  },
  …
}

Two things to handle in the script. A related field comes back as name|code, so we split it and use the code as the option's value. And a boolean facet's key is 1 or 0; use key_as_string, which matches the filter value dogs_allowed=true.

Calling the API from the browser

The page and the API are on different domains, and the request carries an X-API-KEY header. Before sending a request like that, the browser asks the API for permission with a short OPTIONS request, called a preflight. SearchAPI answers it on its own, so there's nothing to configure:

HTTP/2 204
access-control-allow-origin: *
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-headers: Authorization, Content-Type, X-API-KEY
access-control-max-age: 3600

* means any site may call the API, X-API-KEY is on the list of allowed headers, and the browser may reuse this answer for an hour (3600 seconds) instead of asking before every search.

Error responses carry the same headers, so the script can show the message of a 401 or 403 instead of a generic network error. Then we tried what anyone could try from the browser console with the key copied from the page:

POST https://trails.searchapi.net/trails/v1/routes
X-API-KEY: your-read-only-key
Content-Type: application/json

{"route_id": "R-9999", "name": "Fake route"}
{ "status": "error", "type": "forbidden", "code": 403, "message": "Invalid API key" }

Good: the key in the page can't add, change or delete a route. Reading was another story.

Our mistake: the leaders' phone numbers were public

The browser key can't open /leaders, and the page never asks for the leader: its includes list stops at region. So we weren't worried. But every route carries a copy of its leader's visible fields, phone included, and includes is chosen by whoever sends the request, not by us:

GET https://trails.searchapi.net/trails/v1/routes/R-1012?includes=name%2Cleader
X-API-KEY: your-read-only-key
{
  "status": "success",
  "type": "ok",
  "code": 200,
  "message": "OK",
  "data": {
    "name": "Castle Loop",
    "leader": { "leader_id": "L-005", "leader_name": "Mark Fletcher", "leader_phone": "07219 833887" }
  }
}

The same goes for excludes. Both are a way to make responses smaller, not a way to hide fields. A key that may read an endpoint may read every field of its model, including what it embeds from related models. Locking down /leaders didn't help, because the phone had already been copied into the routes.

Fix it in a new API version

The fix is one checkbox: the phone shouldn't be Visible In Related Model. But v1 was live, and a deployed endpoint's model is locked, so we couldn't clear it in place. We built v2 next to it. See API versioning and model locking.

  1. In the sidebar, click APIs, open the API and click Create New Version. v2 starts with the same endpoints, keys and aggregations as v1.
  2. In the sidebar, click Models, edit leaders and click Save As. Name the copy leaders_v2.
  3. Edit leaders_v2, clear Visible In The Related Model on leader_phone and save.
  4. Save routes as routes_v2 the same way. In the copy, delete the leader field and add it again as an object pointing to leaders_v2.
  5. Open the v2 endpoint list. Edit the leaders endpoint and select leaders_v2, then edit the routes endpoint and select routes_v2.
  6. Choose the routes aggregations again. Changing an endpoint's model clears them.
  7. Deploy v2.

Result: the deploy copied all 613 routes and 43 leaders from v1, and each route's leader now carries the id and the name only:

GET https://trails.searchapi.net/trails/v2/routes/R-1012?includes=name%2Cleader
X-API-KEY: your-read-only-key
{
  "status": "success",
  "type": "ok",
  "code": 200,
  "message": "OK",
  "data": { "name": "Castle Loop", "leader": { "leader_id": "L-005", "leader_name": "Mark Fletcher" } }
}

Asking for the phone explicitly is refused, because v2 has no such field:

GET https://trails.searchapi.net/trails/v2/routes/R-1012?excludes=leader.leader_phone
X-API-KEY: your-read-only-key
{
  "status": "error",
  "type": "bad_request",
  "code": 400,
  "message": "Field 'leader.leader_phone' is not allowed for field selection"
}

Last, we changed one line in the page: the API constant now ends in /v2/routes. The same search still returns the same 21 routes.

Don't forget v1

Deploying v2 doesn't switch v1 off. Every version stays live at its own URL, and the browser key worked on both, so for a while the phone numbers were one path segment away. There's no button to delete a version. What closes it is taking the key away: on the version list, we opened Set API Keys on the v1 row, selected the browser key and filtered the list by get. The switch for all listed endpoints already read off, because the leaders' GET endpoints never had this key, so we switched it on and then off again, and saved.

GET https://trails.searchapi.net/trails/v1/routes/R-1012?includes=name%2Cleader
X-API-KEY: your-read-only-key
{ "status": "error", "type": "forbidden", "code": 403, "message": "Invalid API key" }

Where it falls short

For a club site, a small catalog or a directory, this setup does the job. Before you plan around it:

Frequently asked questions

Is it safe to put an API key in client-side JavaScript?
Only a key that may call GET endpoints. Such a key can't create, change or delete records; a POST with it returns 403. It can still read every field of the models it can reach, so keep private data elsewhere.
Can I hide a field from a read-only key?
Not with request parameters: includes and excludes only shape the response the client asks for. Keep the field in a model the browser key can't reach, and don't mark it Visible In Related Model, or every record that links to it carries a copy.
Can I call the API from any domain?
Yes. The API answers the browser's preflight request and sends Access-Control-Allow-Origin: * on its responses. There is no setting that limits a key to your own domain.
What happens when the daily request limit is reached?
The limit is per company and counts every request, whichever key sent it. You get an email at 90% and at 100%; requests are refused with 429 once usage reaches 110% of the daily limit.

Other use cases

All use cases

Try it on your own site

The free Starter plan is enough for a list this size. Import your file under Data Import, create a read-only key, and keep API keys open next to it.

Create a free account