StaticSearch JavaScript search API
470 words, 3-minute read
You can implement whatever input and output functionality or styling you require by directly using the StaticSearch JavaScript API. It can be used when the bind module does not provide the features you require.
staticsearch.find()
method #
The staticsearch.find(<term>)
method returns an array of results for a specific search term:
import { staticsearch } from '/search/staticsearch.js';
const result = await staticsearch.find('my search query');
result
will hold an array of page objects sorted into highest to lowest relevancy order. Each object has the properties:
property | description |
---|---|
id | page ID (number) |
url | page URL from the root path (string) |
title | title/h1 (string) |
date | date in YYYY-MM-DD format (string) |
words | number of words (number) |
relevancy | relevancy score (number) |
Example result:
[
{
"id": 42,
"url": "/news/search-engine-optimization/",
"title": "Do Publican sites rank better?",
"description": "Do static sites rank better in search engines?",
"date": "2025-01-31",
"words": 1234,
"relevancy": 21
},
{
"id": 55,
"url": "/docs/recipe/feeds/txt-sitemap/",
"title": "Create a text sitemap",
"description": "How to output a list of all pages for search engines.",
"date": "2025-02-01",
"words": 954,
"relevancy": 12
},
{
"id": 22,
"url": "/news/site-performance/",
"title": "Are static sites fast?",
"description": "Static sites typically perform better than others.",
"date": "2025-02-22",
"words": 222,
"relevancy": 2
}
]
StaticSearch events #
However a search is initiated, StaticSearch events are triggered on the document
object. These can be used so there’s no need to await
a result or to show result information in any number of components.
staticsearch:find
event #
This is triggered when staticsearch.find()
is run and before any results are available. The search term is available in the event object’s detail.search
property:
// search started
document.addEventListener('staticsearch:find', e => {
// get search term
const { search } = e.detail;
console.log(`searching for "${ search }"`);
});
staticsearch:result
event #
This is triggered when a search result is available. The search term and results array is available in the event object’s detail.search
and detail.result
properties:
// search result available
document.addEventListener('staticsearch:result', e => {
// get search term and result array
const { search, result } = e.detail;
console.log(`${ result.length } pages found for "${ search }"`);
});
Re-run the indexer #
Once you have added StaticSearch functionality to your static site’s templates, you should re-run the indexer to ensure the latest content is indexed.