Skip to main content

Adding Google Custom Search Engine to your site

·2 mins

I’ve added Google CSE recently as Ghost does not come with one initially. I added a custom integration as I did not like the branding that comes with it by default.

The custom integration comes with a 100 free searches per day, and up to 10,000 if you end up purchasing the paid plan.

Create a Custom Search Engine (CSE) #

You’ll need to create a CSE first. Then go ahead and put in the sites you wish to search. For my site, I went ahead and added the whole site to search.

CSE site to search

If you need to exclude any urls from your site, you can go to your search engine in CSE and then go to it’s Setup. Towards the end there will be an Advanced link. Click it and then you can begin excluding urls.

CSE sites to exclude

Grabbing the Search Engine ID #

While you’re on the setup page, make sure to grab your Search Engine ID as well. You’ll find it under the Details section.

CSE search engine id

Creating the Developer CSE Project #

Next you’ll need to head over to Google Developers and create a project for the CSE.

After creating a project, head over to the APIs Library and enable the Custom Search API for your account.

CSE Custom Search API

After enabling, create an API Key. There should be a Credentials link on the same page. Make sure the API key is of the browser type.

CSE Browser API Key

Now isolate the requests to only allow them from trusted domains.

CSE Isolate Requests

Adding the code #

Create the URL as shown below and then use that for any AJAX requests and use that to get your search results.

var endpoint = 'https://www.googleapis.com/customsearch/v1',
    cseId    = 'YOUR SEARCH ENGINE ID',
    apiKey   = 'YOUR API KEY',
    url      = `${endpoint}?key=${apiKey}&cx=${cseId}`;

// Encode the query to search for...
let query = encodeURIComponent(searchInput.value);

// and then send it off using the `q` parameter
fetch(`${url}&q=${query}`)