Building a Full-Stack JavaScript Search Engine with Google Custom Search API

mdshamsfiroz
5 min readOct 17, 2024

--

While exploring the Internet, Have you thought to implement Google searching functionality in your website? Let's do a full-stack JavaScript project that allows users to search for a name on Google and displays the related links. We will be using HTML and Vanilla JavaScript on the front end and Node.js with Express on the back end. The project will leverage the Google Custom Search API to interact with Google’s search engine and return search results

Steps to Implement

Step 1: Set up Google Custom Search API

To get started, you need to configure Google’s Custom Search API and obtain your API credentials.

  1. Create a Project in Google Developer Console:
  • Go to Google Developer Console.
  • Create a new project.

2. Enable Custom Search API:

  • In the API Library, search for “Custom Search API” and enable it.

3. Create a Custom Search Engine (CSE):

  • Go to Google Custom Search Engine and create a new search engine.
  • Specify the websites you want to search (or use * to search the entire web).
  • Copy the Search Engine ID (cx).

4. Get API Key:

  • In the Google Developer Console, go to APIs & Services > Credentials and generate a new API key.

You now have your API key and Search Engine ID (cx), which we’ll use to query Google’s search results.

Step 2: Front-End (HTML + JavaScript)

The front end will be a simple interface where users can enter a search term (name) and view the results.

HTML + CSS + JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Search Engine</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
input[type="text"] {
width: 300px;
padding: 10px;
}
button {
padding: 10px 20px;
cursor: pointer;
}
.results {
margin-top: 20px;
}
.result-item {
margin-bottom: 15px;
}
</style>
</head>
<body>
<h1>Search Name</h1>
<input type="text" id="searchQuery" placeholder="Enter a name...">
<button onclick="search()">Search</button>
<div class="results" id="results"></div>
<script>
async function search() {
const query = document.getElementById('searchQuery').value;
const response = await fetch(`http://localhost:3000/search?name=${query}`);
const data = await response.json();
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '';
data.results.forEach(item => {
const div = document.createElement('div');
div.className = 'result-item';
div.innerHTML = `<a href="${item.link}">${item.title}</a>`;
resultsDiv.appendChild(div);
});
}
</script>
</body>
</html>
  • The HTML creates a search box for user input.
  • The search() function is triggered when the user clicks the "Search" button.
  • It sends an API request to the server, fetches search results, and displays them dynamically.

Step 3: Back-End (Node.js + Express)

The back end will handle requests from the front end, query the Google Custom Search API, and return the results.

Initialize the Project and Install Dependencies

npm init -y
npm install express axios cors dotenv

Create the server.js file with the following code:

// server.js
const express = require('express');
const axios = require('axios');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors());
const GOOGLE_API_KEY = process.env.GOOGLE_API_KEY;
const SEARCH_ENGINE_ID = process.env.SEARCH_ENGINE_ID;
app.get('/search', async (req, res) => {
const { name } = req.query;
if (!name) {
return res.status(400).json({ error: 'Please provide a search term.' });
}
try {
const response = await axios.get('https://www.googleapis.com/customsearch/v1', {
params: {
key: GOOGLE_API_KEY,
cx: SEARCH_ENGINE_ID,
q: name,
}
});
const results = response.data.items.map(item => ({
title: item.title,
link: item.link,
}));
res.json({ results });
} catch (error) {
res.status(500).json({ error: 'Error fetching data from Google Custom Search API' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
  • CORS: We use CORS to allow cross-origin requests from the front end to the back end.
  • Axios: Axios handles HTTP requests to the Google Custom Search API.
  • Environment Variables: Your Google API key and search engine ID are stored in a .env file.

Create a .env file in the root of your project:

GOOGLE_API_KEY=your_google_custom_search_api_key
SEARCH_ENGINE_ID=your_cse_id

Step 4: Run the Application

  1. Make sure your .env file contains the correct API key and search engine ID.
  2. Start the server:
node server.js
  1. Open the index.html file in a browser and enter a name into the search box. The back end will process the search request and return the search results as links.

Explanation

  • Front-End: The front-end consists of a simple HTML form where the user can input a name. When the “Search” button is clicked, it sends a request to the back-end.
  • Back-End: The back-end receives the request, queries Google’s Custom Search API with the name, and sends the results back to the front-end.
  • Google API: Google Custom Search API fetches relevant links based on the name input by the user.

Additional Notes:

  • Error Handling: Make sure to handle errors gracefully on both the front and back ends.
  • CORS: The cors package helps avoid CORS issues when making API requests from the front end.
  • Customization: You can enhance the project by adding features like pagination, filters, or even design improvements.

GitHub Code Link:- https://github.com/mdshamsfiroz/Arth-4-Tasks/tree/main/FullStack/Task5

Below in vs code part, My server is running and in another part, the frontend UI is working when I tried to search India on my own built search engine.

Result Output

Conclusion

This simple full-stack project showcases how you can build a custom search engine using Google’s Custom Search API. With further improvements and additional features, you can make this a powerful tool for specific search purposes.

So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.

Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”

Connect me on Social Media: https://linktr.ee/mdshamsfiroz

Happy coding! Happy learning!

--

--

mdshamsfiroz
mdshamsfiroz

Written by mdshamsfiroz

Trying to learn tool by putting heart inside to make something

No responses yet