DEV Community

Cover image for Adding Search to My Static Site
Alex Hyett
Alex Hyett

Posted on • Originally published at alexhyett.com on

Adding Search to My Static Site

I had a break last weekend from the newsletter as it was the last weekend before my children went back to school. So expect an extra long “Picks of the Week” this week as I have a lot to share!

Apart from taking a break, I did manage to finish off implementing search on my website. Now that I have added my [[5. GARDEN/index|digital garden]] with all my notes, search was sorely lacking. A lot of my notes are isolated thoughts, and therefore it is nearly impossible to find them without going through tags. Now with search, I can search through my notes online in the same way I do with Obsidian.

Search was actually surprisingly simple to set up thanks to Pagefind. If you want to set up search on your static website then keep reading (if not feel free to jump to my “Picks of the Week” below).

Pagefind works by indexing your website after your pages have been rendered using your static site generator. So it doesn't matter if you are using Eleventy like me or something like Hugo, Jekyll or Gatsby.

Adding Pagefind to your site #

The quick start on their website is all you need to implement basic search:

<link href="/pagefind/pagefind-ui.css" rel="stylesheet">
<script src="/pagefind/pagefind-ui.js"></script>
<div id="search"></div>
<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({ element: "#search", showSubResults: true });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Once your website is built you can simply run the following to index:

npx -y pagefind --site public --serve
Enter fullscreen mode Exit fullscreen mode

You will need to replace public with the output directory where your site gets built. If you are using Eleventy then this will likely be _site.

This will index all the text in every HTML file in that directory. This generally isn't what you want as it will also include your article lists, homepage, as well as your menus and footers.

Limiting what gets indexed #

Searching “about” for example would return every page on my website as I have a link to my about page in my footer.

Luckily Pagefind has an option for limiting what parts of your website get indexed. You simply need to add data-pagefind-body to the parts of your website that you want indexed.

For me this was just a case of updating my layout pages for my blog posts and notes, such as:

<article data-pagefind-body>
    {{ content | safe }}
</article>
Enter fullscreen mode Exit fullscreen mode

Sorting the search results #

You probably want to sort your search results by date, so the newest articles are at the top. To do that you need to tell Pagefind what part of your pages have a date on them.

Then simply add the attribute data-pagefind-sort="date" to it. I have a metadata component which contains the published date that I just needed to update.

<div>Published</div><div class="grow-2 ar"><time datetime="{{ page.date | readableDate }}" data-pagefind-sort="date">{{ page.date | readableDate }}</time></div>
Enter fullscreen mode Exit fullscreen mode

You then need to update the script to include the sort setting:

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({
            element: "#search",
            showSubResults: true,
            sort: { date: "desc" }
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Adding custom styling #

When you run the Pagefind command to index your site it will also generate the JavaScript and CSS files that you include in your site. If you want to customise the styling you can simply copy the CSS file, make changes and reference it instead.

There were quite a few tweaks I had to make so it would fit in with the rest of my website.

Gotchas to look out for #

Or things that took up far to my of my time than they should have done!

Results not coming back even though indexed #

When I implemented sorting the first time, I forgot that I have a different metadata component for my notes which I neglected to add data-pagefind-sort="date" to.

As a result none of my notes were coming up in my search results, even though they were indexed. Something to keep in mind if you suddenly have missing results. I wasted a good half an hour trying to track down that bug.

Search not working at all once deployed #

Everything was working locally so I pushed it up my website which is hosted on AWS with CloudFlare in front. At first, I thought it just hadn't updated yet but on further inspection I could see the script and the search div in the code.

Turns out the issue was Cloudflare's Rocket Loader which was messing with the ordering of the scripts. I ended up just turning this off, but you can make some changes to get this to work as mentioned in this GitHub issue.

Mobile zooming in when searching #

This isn't a Pagefind issue but a general UX issue with forms on mobile.

If the font size on your input fields is less than 16px it will cause a weird zooming effect on mobile when you go to type in the field. I hadn't realised that my site was doing this even on my newsletter signup form.

There are various ways to fix this, but the most accessible way is to simply up the font size of your inputs to 16px.


❤️ Picks of the Week #

As mention this is a bit of a chunky “Picks of the Week” as it's really “Picks of the Fortnight”.

There is some good stuff here though!

📝 ArticleThe journey of an internet packet — This a great visual article on understanding how to use traceroute to diagnose network issues. The diagrams really help here.

📝 ArticleJavaScript dates are about to be fixed — Date times in JavaScript are just a mess. I have spent a lot of time at work recently trying to get this right with a colleague, and it is painful at how difficult it still is in JavaScript.

👾 GameVim Racer — I am trying to get better at the VIM shortcuts, so I can navigate around code faster. This game looks like it could be a fun way to learn them.

📝 ArticleLidl's Cloud Gambit — Of all the companies to become the next AWS, I would never have guessed Lidl. Let's hope they bring their cheap prices to the cloud too.

📝 ArticleDatabase "sharding" came from Ultima Online? (2009) — I have always wondered where the term “sharding” comes from. I have used the word a lot over the years and never knew where it originated from.

📝 ArticleDokku: My favorite personal serverless platform — I still use AWS and Railway (affiliate link, get $20 free credit) for my personal projects, but I really should give something like Dokku a try. The other one that I have heard good things about is Coolify.

📝 ArticleRaw dog the open web! — This is one of the reasons I have my “Picks of the Week”. Sharing is something that is inherently human, and we really should do more of it instead of relying on algorithms.

📝 ArticleThe Monospace Web — I like monospace fonts, I think it is spending so much time in a code editor that does it. I am not quite at embracing monospace on my website, but this does make me consider it.

📝 ArticleA Collection of Free Public APIs That Is Tested Daily — Having a set of APIs you can use is great if you want to create a new project to learn a new language. Why not try one of these?

📝 ArticleUsing Fibonacci numbers to convert from miles to kilometers and vice versa — It is a nice coincidence that the Golden Ratio is similar to the difference between miles and kilometres. To be honest I usually just multiply by 1.5 which is easier to do in my head.

📝 ArticleOpenAI is good at unminifying code — I don't like using AI for things that require creative thinking. If we resort to AI instead of drawing or writing then we will lose those creative muscles. Using it for unminifying code though is a good use though.

📝 ArticleChrome is entrenching third-party cookies that will mislead users — Friends don't let friends use Chrome. Seriously, Chrome is getting ridiculous. Try Firefox instead.

📝 ArticleThe secret inside One Million Checkboxes — This is ingenious!

📝 ArticleBuilding LLMs from the Ground Up: A 3-Hour Coding Workshop — I don't think AI is going anywhere, and it is going to become a requirement soon to understand how AI works.

📝 ArticleOAuth from First Principles — If you are a “Silicon Valley” fan then you will appreciate this post. It also a very good explanation of OAuth.

📝 ArticleReasons to write design docs — Not being able to communicate yourself effectively often holds many developers back. We use design docs all the time at work and they are really helpful.

🛠️ ToolOrbStack: The fast, light, and easy way to run Docker containers and Linux — I am keen to give this a try. I don't have an issue with Docker Desktop, but that might be as I have decent specced computers. If you are finding Docker a bit of resource hog you may want to give this a try.

🛠️ ToolA "New Way" to Pay Creators — This would be great if it became standard and was added into browsers by default. I started my “One a Month” club to try to get some support for my writing, but I have only had 1 person sign up so far.

📝 ArticleNotes on Distributed Systems for Young Bloods — There is some great advice in here for writing distributed systems. Everything gets harder once you move into distributed architecture.

📝 ArticleThe Art of Finishing — I am terrible at finishing projects. I have so many ideas that I start but never get round to completing. At least I have stopped buying domain names for them!

📝 ArticleGreppability is an underrated code metric — This is some good advice when it comes to naming. IDEs are generally quite good at finding references for things but even then it can struggle. The one about not using interpolated strings for DB tables is a definite must.

🛠️ ToolYi-Coder: A Small but Mighty LLM for Code — I use AI to write the odd bash script for me, and it does save me a lot of time. This looks like a good option for running locally. I am not sure how it stacks up against other local LLMs though.

🛠️ ToolAnythingLLM — I tried setting up RagFlow recently. I did eventually get it working, but it was such a hassle (at least on Apple Silicon). This looks like a great alternative, especially if you want to ask it questions on documents. I would love to be able to import one of my e-books and be able to ask it questions.


💬 Quote of the Week #

“Money is not a substitute for tenderness, and power is not a substitute for tenderness. I can tell you, as I'm sitting here dying, when you most need it, neither money nor power will give you the feeling you're looking for, no matter how much of them you have.”

From the book "Tuesdays with Morrie" by Mitch Albom.

Top comments (0)