Build a Node.js Interactive Web-Based Product Catalog

Written by

in

In today’s digital landscape, businesses of all sizes need a way to showcase their products effectively. A well-designed product catalog is essential for attracting customers, providing information, and ultimately, driving sales. While there are numerous e-commerce platforms available, sometimes you need a custom solution that fits your specific needs. This tutorial will guide you through building an interactive web-based product catalog using Node.js, Express, and a touch of HTML, CSS, and JavaScript. We’ll focus on creating a functional and user-friendly catalog that you can adapt and expand upon.

Why Build Your Own Product Catalog?

You might be wondering why you’d want to build a product catalog from scratch when there are existing solutions. Here are a few compelling reasons:

  • Customization: You have complete control over the design, features, and functionality. You can tailor the catalog to perfectly match your brand and specific product requirements.
  • Learning: Building a project like this is an excellent way to learn and practice Node.js, Express, and web development fundamentals.
  • Cost: For simple catalogs, building your own can be more cost-effective than subscribing to a paid platform, especially in the early stages of a business.
  • Integration: You can easily integrate your custom catalog with other systems, such as a CRM or inventory management system.

What We’ll Build

We’ll create a basic product catalog with the following features:

  • Product Display: A list of products with their names, descriptions, and images.
  • Product Details: A detailed view of each product when clicked.
  • Simple Filtering (Optional): The ability to filter products by category or other attributes.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  • Node.js and npm (Node Package Manager): You can download these from the official Node.js website (nodejs.org).
  • A Text Editor or IDE: Such as Visual Studio Code, Sublime Text, or Atom.

Setting Up the Project

Let’s start by creating a new project directory and initializing it with npm. Open your terminal or command prompt and run the following commands:

mkdir product-catalog
cd product-catalog
npm init -y

This will create a new directory called product-catalog, navigate into it, and initialize a package.json file with default settings. The -y flag automatically accepts the default values.

Installing Dependencies

Next, we’ll install the necessary dependencies. We’ll use:

  • Express: A web application framework for Node.js.
  • EJS (Embedded JavaScript): A templating engine for generating HTML.

Install these dependencies using npm:

npm install express ejs

Project Structure

Let’s create the following project structure:

product-catalog/
├── app.js             // Main application file
├── package.json
├── views/
│   ├── index.ejs      // Home page
│   ├── product.ejs    // Product detail page
│   └──partials/
│       └── header.ejs // Header
│       └── footer.ejs // Footer
├── public/
│   ├── css/
│   │   └── style.css  // CSS styles
│   ├── img/
│   │   └── product1.jpg // Example product image
│   └── js/
│       └── script.js  // JavaScript (optional)

This structure organizes our code and assets logically. The views directory will contain our EJS templates, the public directory will hold static assets like CSS, images, and JavaScript, and app.js will be our main application file.

Creating the Express Application (app.js)

Let’s start by writing the code for app.js. This file will set up our Express application, define routes, and handle requests.

// app.js
const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(express.static(path.join(__dirname, 'public'))); // Serve static files

// Set the view engine to EJS
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Sample product data (replace with your actual data)
const products = [
 {
  id: 1,
  name: 'Product 1',
  description: 'This is the description for Product 1.',
  image: '/img/product1.jpg',
  price: 19.99,
  category: 'Electronics',
 },
 {
  id: 2,
  name: 'Product 2',
  description: 'This is the description for Product 2.',
  image: '/img/product1.jpg',
  price: 29.99,
  category: 'Clothing',
 },
 // Add more products here
];

// Routes
app.get('/', (req, res) => {
 res.render('index', { products: products });
});

app.get('/product/:id', (req, res) => {
 const productId = parseInt(req.params.id);
 const product = products.find((p) => p.id === productId);

 if (product) {
  res.render('product', { product: product });
 } else {
  res.status(404).send('Product not found');
 }
});

// Start the server
app.listen(port, () => {
 console.log(`Server is running on port ${port}`);
});

Here’s a breakdown of the code:

  • Importing Modules: We import the express module and the path module, which is used to work with file paths.
  • Creating the App: We create an instance of the Express application.
  • Setting the Port: We define the port the server will listen on, using an environment variable (process.env.PORT) or defaulting to 3000.
  • Middleware:
    • express.static(path.join(__dirname, 'public')): This middleware serves static files like CSS, images, and JavaScript from the public directory.
  • Setting the View Engine:
    • app.set('view engine', 'ejs'): This tells Express to use EJS as the templating engine.
    • app.set('views', path.join(__dirname, 'views')): This sets the directory where the view templates are located.
  • Sample Product Data: We define an array of products. In a real-world application, this data would likely come from a database.
  • Routes:
    • app.get('/', (req, res) => { ... }): This route handles requests to the root URL (/). It renders the index.ejs template and passes the products data to it.
    • app.get('/product/:id', (req, res) => { ... }): This route handles requests to URLs like /product/1. It extracts the product ID from the URL, finds the corresponding product in the products array, and renders the product.ejs template, passing the product data to it. It also handles the case where the product is not found, returning a 404 error.
  • Starting the Server: app.listen(port, () => { ... }) starts the server and listens for incoming requests on the specified port.

Creating the EJS Templates

Now, let’s create the EJS templates for our product catalog. We’ll start with the header and footer, which will be included in both the index and product detail pages.

Header (views/partials/header.ejs)

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Product Catalog</title>
 <link rel="stylesheet" href="/css/style.css">
</head>
<body>
 <header>
  <h1>My Product Catalog</h1>
  <nav>
   <!-- Add navigation links here -->
  </nav>
 </header>
 <main>

Footer (views/partials/footer.ejs)

© 2024 My Product Catalog</p>
 </footer>
</body>
</html>

Index Page (views/index.ejs)

This is the main page that displays the list of products.


  <p>Price: $<%= product.price %></p>
  </a>
  </li>
  <% }); %>
  </ul>
 </section>

<%- include('partials/footer') -%>

In this template:

  • We include the header and footer using <%- include('partials/header') -%> and <%- include('partials/footer') -%>.
  • We loop through the products array using products.forEach(...).
  • For each product, we display its image, name, description, and price.
  • We create a link to the product detail page using <a href="/product/<%= product.id %>">.

Product Detail Page (views/product.ejs)

This page displays the details of a specific product.


  <p>Price: $<%= product.price %></p>
  <p>Category: <%= product.category %></p>
  <!-- Add more product details here -->
  <a href="/">Back to Products</a>
 </section>

<%- include('partials/footer') -%>

In this template:

  • We include the header and footer.
  • We display the product’s details, including its name, image, description, price, and category.
  • We provide a link back to the product list page.

Adding CSS Styles (public/css/style.css)

Let’s add some basic CSS to style our product catalog. Create a file named style.css in the public/css/ directory and add the following styles:

body {
 font-family: sans-serif;
 margin: 0;
 padding: 0;
 background-color: #f4f4f4;
}

header {
 background-color: #333;
 color: #fff;
 padding: 1em 0;
 text-align: center;
}

nav {
 /* Add navigation styles here */
}

main {
 padding: 20px;
}

.products {
 display: flex;
 flex-wrap: wrap;
 justify-content: center;
}

.products li {
 list-style: none;
 margin: 10px;
 padding: 10px;
 border: 1px solid #ddd;
 background-color: #fff;
 width: 250px;
 text-align: center;
}

.products img {
 max-width: 100%;
 height: auto;
 margin-bottom: 10px;
}

.product-detail {
 padding: 20px;
 border: 1px solid #ddd;
 background-color: #fff;
}

.product-detail img {
 max-width: 300px;
 height: auto;
 margin-bottom: 10px;
}

These styles provide basic styling for the header, product list, and product detail pages. Feel free to customize these styles to match your brand’s aesthetics.

Running the Application

Now that we’ve set up our application and templates, let’s run it. In your terminal, navigate to the project directory (product-catalog) and run the following command:

node app.js

This will start the server, and you should see a message in the console indicating that the server is running (e.g., “Server is running on port 3000”). Open your web browser and go to http://localhost:3000. You should see the product catalog with the list of products. Clicking on a product should take you to the product detail page.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • 404 Not Found:
    • Problem: You might encounter a 404 error if the server can’t find the requested resource (e.g., a CSS file, an image, or a product detail page).
    • Solution: Double-check the file paths in your HTML and CSS code. Make sure that the files are in the correct directories and that the paths are relative to the public folder. Also, verify that the routes in app.js are correctly defined.
  • EJS Template Errors:
    • Problem: Errors in your EJS templates can prevent the page from rendering correctly.
    • Solution: Check the console for error messages. Ensure that your EJS syntax is correct (e.g., using <%= ... %> for outputting data and <% ... %> for control structures).
  • Incorrect File Paths:
    • Problem: Images not displaying or CSS not being applied.
    • Solution: Double-check the paths to your images and CSS files in your HTML. Remember that the paths are relative to the public directory.
  • Server Not Starting:
    • Problem: The server may not start due to errors in your app.js file.
    • Solution: Check the console for error messages. Ensure that you have installed all the necessary dependencies (Express, EJS) and that your code has no syntax errors.

Adding More Features

Here are some ideas for expanding your product catalog:

  • Database Integration: Instead of hardcoding the product data, connect to a database (e.g., MongoDB, PostgreSQL, MySQL) to store and retrieve product information. This allows you to easily manage a large number of products.
  • Product Categories and Filtering: Implement filtering options to allow users to filter products by category, price, or other attributes.
  • Search Functionality: Add a search bar to enable users to search for products by name or description.
  • User Authentication: Implement user authentication to allow users to create accounts, save favorites, or place orders.
  • Shopping Cart: Create a shopping cart feature so users can add products to their cart and checkout.
  • Responsive Design: Make the catalog responsive so it looks good on all devices (desktops, tablets, and smartphones).
  • Image Optimization: Optimize images for web performance to ensure fast page load times.

Key Takeaways

  • This tutorial provided a step-by-step guide to building a basic, interactive product catalog using Node.js, Express, and EJS.
  • You learned how to set up an Express application, define routes, create EJS templates, and serve static files.
  • You gained practical experience with essential web development concepts like routing, templating, and serving static assets.
  • You learned about common mistakes and how to fix them.

FAQ

1. How do I deploy this product catalog to the internet?

You can deploy your product catalog to a platform like Heroku, Netlify, or AWS. You’ll need to create an account, upload your code, and configure the platform to run your Node.js application.

2. How can I add more product details?

You can add more product details by modifying the product data in the products array (or your database) and updating the product.ejs template to display the new information.

3. How do I add product images?

Place your product images in the public/img directory. In your EJS templates, use the correct image paths (e.g., <img src="/img/product1.jpg" ...>).

4. Can I use a different templating engine?

Yes, you can use other templating engines like Pug (formerly Jade) or Handlebars. You’ll need to install the appropriate package and configure Express to use it.

Conclusion

Building your own product catalog with Node.js is a rewarding project that allows you to gain a deeper understanding of web development and create a customized solution for your needs. By following the steps outlined in this tutorial and experimenting with the suggested enhancements, you can create a powerful and flexible product catalog that showcases your products effectively. Remember to continuously refine and improve your catalog, and don’t be afraid to experiment with new features and technologies. The possibilities are endless, and your custom catalog can evolve along with your business, adapting to its unique requirements and providing a seamless experience for your customers. By taking the initiative to build your own, you’re not just creating a product catalog; you’re building a foundation for your online presence, empowering your business to thrive in the digital age.