Part 83: Enhancing Your Cart: Adding Items with a POST Request
[Pages] Shopping Cart (Exercises)

After successfully displaying all items in your cart, the next natural step in creating a seamless shopping experience is to allow users to add items to their cart. In this post, we'll explore how to implement this feature by making authenticated POST requests to your backend API. This guide will walk you through modifying your API route to handle POST requests efficiently.
Step 1: Update the API Route
Our existing API endpoint for handling cart operations currently supports fetching cart items using a GET request. To enable adding items, we'll extend this endpoint to handle POST requests by creating a new handler function.
Modifying the Cart Handler
We need to distinguish between GET and POST requests within our cart route. We'll do this by renaming the existing handler and introducing a new one:
// File: pages/api/cart.js
function stripCartItem(cartItem) {
// Function to strip unnecessary properties
return {
id: cartItem.id,
product: cartItem.product.id,
quantity: cartItem.quantity,
};
}
async function handleGetCart(req, res) {
const { jwt } = req.cookies;
if (!jwt) {
res.status(401).end();
return;
}
// Fetch and return cart items logic
}
async function handlePostCart(req, res) {
const { jwt } = req.cookies;
if (!jwt) {
res.status(401).end();
return;
}
const { productId, quantity } = req.body;
try {
await fetchJson(`${CMS_URL}/cart-items`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${jwt}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ product: productId, quantity }),
});
res.status(200).json({});
} catch (err) {
res.status(401).end();
}
}
async function handleCart(req, res) {
switch (req.method) {
case 'GET':
return handleGetCart(req, res);
case 'POST':
return handlePostCart(req, res);
default:
res.status(405).end();
}
}
export default handleCart;Explanation
JWT Authentication: Both handlers check for a valid JSON Web Token in the request cookies. If absent, they return a 401 Unauthorized status.
Request Handling: The
handleCartfunction uses a switch statement to determine the request method. It callshandleGetCartfor GET requests andhandlePostCartfor POST requests.POST Request Logic: The
handlePostCartfunction extractsproductIdandquantityfrom the request body and sends a POST request to the CMS to add the item to the cart.
Step 2: Test the Implementation
To verify our implementation, we can manually test the POST request using the browser's console or a tool like Postman. The request should look like this:
fetch('/api/cart', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ productId: 3, quantity: 1 }),
})
.then(response => response.json())
.then(data => console.log(data));Expected Outcome
After executing the POST request, you should see the new item added to the cart. If your CMS is set up correctly, the cart should reflect the addition, showing the new product along with its quantity.
Conclusion
By implementing the ability to add items to the cart, you have taken a significant step towards a fully functional e-commerce application. This feature enhances the user experience by allowing seamless interaction with the cart. As you continue to develop your application, consider adding further functionalities such as updating or removing items from the cart, ensuring a comprehensive shopping experience for your users.
Last updated