How to Implement a Shopping Cart in ExpressJS

Updated: January 22, 2024 By: Guest Contributor Post a comment

Introduction

Building a robust shopping cart is essential for any e-commerce website. In this tutorial, we will go through the step-by-step process of implementing a user-friendly shopping cart using ExpressJS, a fast, unopinionated, minimalist web framework for Node.js. This guide includes valuable tips and code examples that are practical and easily adaptable for your ExpressJS application.

Before we start, you should have Node.js and npm (Node Package Manager) installed on your machine. Basic knowledge of JavaScript and an understanding of RESTful APIs would be beneficial.

Step-by-Step Instructions

Step 1 – Setting Up ExpressJS

Firstly, initialize a new Node.js project and install ExpressJS:

$ mkdir express-cart
$ cd express-cart
$ npm init -y
$ npm install express --save

Now we create an app.js file, which will be the entry point to our application:

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

app.get('/', (req, res) => {
    res.send('Welcome to the shopping cart tutorial!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Step 2 – Structuring the Shopping Cart

To manage cart items, we create a simple in-memory structure. In a production environment, you would typically use a database for storage.

// A simple in-memory cart structure
let cart = [];

Step 3 – Adding Items to the Cart

We create an endpoint that allows items to be added to the cart:

// Add a middleware to parse JSON
app.use(express.json());

app.post('/add-to-cart', (req, res) => {
    const { itemId, quantity } = req.body;
    // Imagine we retrieved item details from the database
    const item = { itemId, quantity, name: 'Item Name', price: 19.99 };
    
    const existingItemIndex = cart.findIndex(i => i.itemId === itemId);
    if (existingItemIndex > -1) {
        cart[existingItemIndex].quantity += quantity;
    } else {
        cart.push(item);
    }
    
    res.status(200).json({ message: 'Item added to cart', cart });
});

Step 4 – Removing Items from the Cart

To remove items from the cart, we create another endpoint:

app.post('/remove-from-cart', (req, res) => {
    const { itemId } = req.body;
    cart = cart.filter(item => item.itemId !== itemId);
    res.status(200).json({ message: 'Item removed from cart', cart });
});

Step 5 – Updating Cart Quantity

To update the quantity of an item in the cart:

app.post('/update-cart', (req, res) => {
    const { itemId, quantity } = req.body;
    const item = cart.find(item => item.itemId === itemId);
    if (item) {
        item.quantity = quantity;
    }
    res.status(200).json({ message: 'Cart updated', cart });
});

Step 6 -Viewing the Cart (Optional)

To retrieve the current state of the shopping cart:

app.get('/cart', (req, res) => {
    res.status(200).json({ cart });
});

Step 7 – Checkout Process

The checkout process would involve several steps, including validating cart items, calculating the total cost, and implementing payment gateways. This can get fairly complex, and we will cover this in another tutorial. As a starting point, here is a basic checkout endpoint:

app.post('/checkout', (req, res) => {
    // Simplified checkout process
    if(cart.length == 0) {
        return res.status(400).json({ message: 'Cart is empty' });
    }
    
    const total = cart.reduce((acc, item) => acc + (item.price * item.quantity), 0);
    
    // Implement payment gateway logic here
    
    // Once payment is successful, empty the cart
    cart = [];
    
    res.status(200).json({ message: 'Checkout successful', total });
});

Conclusion

In this tutorial, we have demonstrated how to build a basic shopping cart using ExpressJS. We’ve covered adding, updating, and removing items, as well as viewing the cart and a simple checkout process. For a production-ready shopping cart, further enhancements like database integration, session management, error handling, and payment gateway integration would be required. Happy coding!