Adding search to a static site

[Jan 10, 2022]

This blog post is based off this tweet reply. Because I read it and thought “oh, I already did write about this!” then tried searching for it on the site and couldn’t find it by clicking around, so I searched in the files for the site on my computer and couldn’t find it, then searched across my entire computer and found a long blog post about using Lunr to search gifs that I never finished1.

So, here’s a finished version in a similar vein: let’s add search functionality to this site using Lunr. We need to build an index for Lunr at build time, which means we need some piece of code that will be triggered to begin looking for items to add. I did this by creating a new Search page (/search). I copied the logic from my index page and removed some logic that isn’t relevant, but the code here gets all of the markdown files in my content folder and then loops through them. In this case we want to build a “document” structure for Lunr to be able to search through:

1export async function getStaticProps({ ...ctx }) { 2 //get posts & context from folder 3 const posts = ((context) => { 4 const keys = context.keys(); 5 const values = keys.map(context); 6 const data = keys.map((key, index) => { 7 const value = values[index]; 8 // Parse yaml metadata & markdownbody in document 9 const document = matter(value.default); 10 document.data.date = singleDateFormat(document.data.date); 11 if (document.data.finished) { 12 document.data.finished = singleDateFormat(document.data.finished); 13 } 14 15 return { 16 title: document.data.title || "", 17 body: document.content || "", 18 slug: key.replace(".md", "").substring(1), 19 }; 20 }); 21 22 return data; 23 })(require.context("../content", true, /\.\/.*\.md$/)); 24 25 return { 26 props: { 27 searchData: posts, 28 }, 29 }; 30}

In the actual Search page component itself, we build the Lunr index from the searchData prop:

1 const lunrIndex = lunr(function () { 2 this.ref("title"); 3 this.field("title"); 4 this.field("body"); 5 this.field("slug"); 6 7 props.searchData.forEach(function (doc) { 8 this.add(doc); 9 }, this); 10});

After this we wire up the Search page to have a text input that, on change, searches the Lunr index. This is the code for the entire page2:

1function Search(props) { 2 const [searchString, setSearchString] = useState(""); 3 const [searchResults, setSearchResults] = useState(); 4 var lunrIndex = lunr(function () { 5 this.ref("title"); 6 this.field("title"); 7 this.field("body"); 8 this.field("slug"); 9 10 props.searchData.forEach(function (doc) { 11 this.add(doc); 12 }, this); 13 }); 14 15 const searchLunr = (e) => { 16 setSearchString(e.target.value); 17 setSearchResults(lunrIndex.search(e.target.value)); 18 }; 19 20 const searchResultsList = () => { 21 if (!searchResults || !searchResults.length) { 22 return null; 23 } 24 return searchResults.map((result) => { 25 const slug = props.searchData.find( 26 (data) => data.title === result.ref 27 ).slug; 28 return ( 29 <li key={slug}> 30 <p>{result.ref}</p> 31 <Link href={`/${slug}`}>{slug}</Link> 32 </li> 33 ); 34 }); 35 }; 36 37 return ( 38 <Layout> 39 <ReadingContent> 40 <h1>Search</h1> 41 <input type="text" value={searchString} onChange={searchLunr} /> 42 <h2>Results</h2> 43 <ul>{searchResultsList()}</ul> 44 </ReadingContent> 45 </Layout> 46 ); 47}

So that’s cool, and it works, but one thing I noticed here is that this Lunr search runs against the full text of the content, but once you click through, if the post is long it’s not immediately obvious where the term you were searching for appears. Let’s do something about that, at least for blog content.

First, let’s append a query parameter to the link we get from our search results, like this:

1<Link href={`/${slug}?searchterm=${searchString}`}>{slug}</Link>

This blog is built with Next so for me getting that query parameter on any given page looks something like:

1import { useRouter } from "next/router"; 2 3// inside the component 4const { query } = useRouter(); 5const searchTerm = query.searchterm;

All of the post content is written in Markdown, so we can pass the post body to a function that looks for the search term in the string and replaces it, like this:

1const wrapSearchTerm = (string) => { 2 if (searchTerm) { 3 const regex = new RegExp(`${searchTerm}`, "g"); 4 return string.replace( 5 regex, 6 `<span class="searchTerm">${searchTerm}</span>` 7 ); 8 } 9 return string; 10 };

One thing I realized was doing it this way breaks links that might have the search term in it, because the searching is happening on the unprocessed Markdown. Running it post processing would be better, but to be lazy, let’s just search for the word with a reasonable set of boundaries to ignore, like this:

1const regex = new RegExp(`${searchTerm}(?![-_])`, "g");`

which eliminates most slugified versions of the word. It’s still case sensitive but the 80/20 among its users (me) says it’s good enough to ship.


  1. For good reason, the original post was about recreating Giphy using Lunr and lambda functions. Those parts were fine, but I think I lost the thread trying to make a Slackbot to tie them together.
  2. This is React with some wrapping components like Layout and ReadingContent that only handle styling.

Comments? Questions? Just want to say hi? Get in touch.

Back to top