ariya.io About Talks Articles

Search Box and Cloud Function

2 min read

For a blog hosted with Firebase Hosting, it turns out that a little search box is fairly easy to implement by using Cloud Functions for Firebase.

As with the current trend nowadays, this blog is a static site prepared with Hugo and deployed to Firebase (see my previous blog: Static Site with Hugo and Firebase). Some time ago, I realized that since I am using Firebase anyway, might as well take advantage of its Cloud Functions to add a little search functionality to the blog, particularly for its 404 page.

search box

Of course, I am cheating a little bit. Using the above search box actually just redirects the search to my favorite search engine, DuckDuckGo, resulting in the following:

DuckDuckGo search

Implementing it is almost trivial. First, we need index.js inside the functions subdirectory with the content as short as this (obviously, for your blog, replace site accordingly):

const functions = require('firebase-functions');
exports.search = functions.https.onRequest((request, response) => {
  const q = request.query.q || '';
  response.redirect(`https://duckduckgo.com/?q=site:ariya.io+${q}`);
});

Once it is properly deployed, the trigger URL will be in the form of us-central1-YOURFIREBASEPROJECT.cloudfunctions.net/search. This is rather ugly. To overcome that, set up a rewrite inside firebase.json so that it looks something like:

{
    "hosting": {
      "rewrites": [{
          "source" : "/search",
          "function": "search"
        }
      ]
    }
  }

and thus, the function is available as the top-level /search of your Firebase Hosting URL, including if it is a custom domain.

After this, inserting the search box is also equally fun:

<form action="/search">
<p><input type="text" name="q" required> <button type="submit">Search</button></p>
</form>

When a visitor uses the search, they will get redirected to DuckDuckGo and be presented with the search result. Fast and easy!

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook