Adding Search to Your Site Using Google

Google Programmable Search Engine - no server-side code needed!

Introduction

I wanted to add search to this site. Whilst it doesn’t have a lot of content right now I’m confident it will continue to grow and for me I might want to quickly find something from deep history in the future. My requirements were quite simple:

  • Must work just fine with a Hugo static site.
  • Minimal or no server-side code. It’s something else to maintain and goes contrary to my aims of keeping this site as simply as possible.
  • Integrate with the site design and not be a visible “off-site” engine. It’s neater and presents a consistent user experience.
  • Be open-source or provided by a large vendor. This reduces the changes of it disappearing any time soon.

Solution

I spotted on one of my favourite sites, BoingBoing, that they used Google Custom Search. My interest piqued, I went and had a look.

Enter Google Programmable Search Engine. It meets all my requirements and with minimal coding.

How it works

I’m using the Custom Search JSON API, don’t use the alternate Custom Search Site Restricted JSON API as it’s deprecated and will die end of 2024.

I followed the docs https://developers.google.com/custom-search/v1/introduction. What you need to do:

  • Get an API key.
  • Lock down the API key to your domain. https://www.jamieakers.co.uk/* here, and also my localhost for development. This prevents anyone on the open internet using your key elsewhere as you will be publishing it publically (and yes, this is fine!).

Then, a quick bit of jQuery to take the results from a form, make an AJAX request to Google and get the results.

  • Key is your API key, CX is the ID of your search. You can find this in the URL when you are viewing the Custom Search.
  • Issue a GET request to https://www.googleapis.com/customsearch/v1?q=SEARCH QUERY&cx=CX&key=KEY
  • (all the usual error handling)
  • Iterate over data.items and add to the page…
    • A hyperlink to result.link with text result.htmlTitle
    • A description of result.htmlSnippet

I also do a few other niceties, like populate the search box with the original query and a loading spinner. You can view my source code to see exactly how it works.

  technology

  web