Part 80: Building a Custom API Route to Fetch and Display Cart Items

[Pages] Shopping Cart (Exercises)

[Pages] Shopping Cart (Exercises)

Creating a fully functional shopping cart is a crucial aspect of any e-commerce application. In this blog post, we will discuss how to implement a custom API route to securely fetch cart items and display them on the cart page. This involves fetching data from a CMS while ensuring user authentication via JSON Web Tokens (JWT).

The Challenge

We need to display cart items on our cart page. However, due to security concerns, we cannot directly access the CMS from the frontend. Instead, we'll create a new API route in our application to handle this request securely. This API route will extract the necessary data from the CMS and return a simplified response to the frontend.

Implementing the API Route

Step 1: Creating the API Route

First, let's create a new API route to fetch the cart items. We'll add a file named cart.js in the pages/api directory of our project.

// File: pages/api/cart.js

import { fetchJson } from '../../lib/api';

const { CMS_URL } = process.env;

// Function to strip unnecessary fields from the cart item
function stripCartItem(cartItem) {
  return {
    id: cartItem.id,
    product: {
      id: cartItem.product.id,
      title: cartItem.product.title,
      price: cartItem.product.price,
    },
    quantity: cartItem.quantity,
  };
}

async function handleCart(req, res) {
  const { jwt } = req.cookies; // Extract JWT from cookies
  if (!jwt) {
    res.status(401).end(); // Unauthorized if no JWT
    return;
  }
  try {
    // Fetch cart items from CMS
    const cartItems = await fetchJson(`${CMS_URL}/cart-items`, {
      headers: { 'Authorization': `Bearer ${jwt}` },
    });
    // Strip unnecessary data and send response
    res.status(200).json(cartItems.map(stripCartItem));
  } catch (err) {
    res.status(401).end(); // Handle errors
  }
}

export default handleCart;

Step 2: Understanding the Code

  1. JWT Authentication: We extract the JWT from the request cookies to authenticate the user. If the token is missing, we respond with a 401 status code indicating unauthorized access.

  2. Data Fetching: Using the fetchJson utility function, we make a request to the CMS's /cart-items endpoint. The JWT is included in the authorization header to authenticate the request.

  3. Data Transformation: We define a stripCartItem function to transform the cart items into a simplified format, retaining only the necessary fields: id, product.id, product.title, product.price, and quantity.

  4. Error Handling: We catch any errors during the fetch operation and respond with a 401 status code if something goes wrong.

Testing the API Route

To test this API route, you can use the browser's JavaScript console to make a fetch request to /api/cart. Once the route is implemented, calling this endpoint should return a JSON response with the cart items, each containing the specified fields.

Conclusion

By implementing this API route, we've securely enabled the frontend to access cart items while ensuring user authentication. This approach allows us to control the data flow between the client and the CMS, enhancing both security and performance. In the next steps, we'll focus on consuming this API endpoint from the frontend to display the cart items on the cart page.

This implementation is a foundational part of building a robust e-commerce application, where managing and displaying user-specific data securely is paramount. Stay tuned for further enhancements and features to make our shopping cart fully functional.

Last updated