Discover how to build a custom shopping cart with Lovable using our step-by-step guide. Boost your eCommerce site with practical tips and best practices.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Starting a New Lovable Project
index.html
, styles.css
, and script.js
.
Setting Up the HTML Structure
index.html
file and set up a basic HTML template.index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart with Lovable</title>
<link rel="stylesheet" href="styles.css">
<!-- Include any external libraries via CDN if necessary (e.g., jQuery) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<header>
<h1>My Shopping Cart</h1>
</header>
<main>
<section id="product-list">
<h2>Products</h2>
<!-- Example product items -->
<div class="product" data-name="Product 1" data-price="19.99">
<p>Product 1 - $19.99</p>
<button class="add-to-cart">Add to Cart</button>
</div>
<div class="product" data-name="Product 2" data-price="29.99">
<p>Product 2 - $29.99</p>
<button class="add-to-cart">Add to Cart</button>
</div>
</section>
<section id="shopping-cart">
<h2>Shopping Cart</h2>
<ul id="cart-items">
<!-- Cart items will be dynamically inserted here -->
</ul>
<p id="total">Total: $0.00</p>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
Adding Styling with CSS
styles.css
file and add styles for the shopping cart components.styles.css
file:
/_ Reset some default styles _/
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
header, main {
max-width: 800px;
margin: auto;
}
h1, h2 {
text-align: center;
}
/_ Product list styles _/
#product-list {
margin-bottom: 40px;
}
.product {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
text-align: center;
}
.add-to-cart {
background-color: #28a745;
border: none;
color: white;
padding: 5px 10px;
cursor: pointer;
}
/_ Shopping cart styles _/
#shopping-cart {
border-top: 2px solid #333;
padding-top: 20px;
}
#cart-items {
list-style-type: none;
padding: 0;
}
#cart-items li {
border-bottom: 1px solid #ccc;
padding: 10px 0;
}
Implementing the Shopping Cart Logic
script.js
file and implement the JavaScript logic to add products to the cart, update totals, and display cart items.index.html
) to simplify DOM manipulation. Copy the code into your script.js
file:
$(document).ready(function () {
var cart = [];
// Function to update the shopping cart display
function updateCart() {
var total = 0;
var $cartItems = $('#cart-items');
$cartItems.empty();
$.each(cart, function(index, item) {
total += parseFloat(item.price);
$cartItems.append('<li>' + item.name + ' - $' + parseFloat(item.price).toFixed(2) + '</li>');
});
$('#total').text('Total: $' + total.toFixed(2));
}
// Event listener for adding products to the cart
$('.add-to-cart').on('click', function () {
var $product = $(this).closest('.product');
var name = $product.data('name');
var price = $product.data('price');
cart.push({ name: name, price: price });
updateCart();
});
});
Integrating Additional Dependencies
index.html
head section.index.html
before your own script references:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
Testing the Shopping Cart
Final Considerations and Customizations
script.js
and modifying index.html
to include new user interface elements.
const express = require('express');
const app = express();
app.use(express.json());
let shoppingCart = {};
function createCartItem(productId, { name, price }) {
return {
productId,
name,
price,
quantity: 1,
loveCount: 0
};
}
app.post('/api/cart/add', (req, res) => {
const { productId, name, price } = req.body;
if (!productId || !name || !price) {
return res.status(400).json({ error: 'Missing product data' });
}
if (shoppingCart[productId]) {
shoppingCart[productId].quantity += 1;
} else {
shoppingCart[productId] = createCartItem(productId, { name, price });
}
res.json({ message: 'Item added', cart: shoppingCart });
});
app.post('/api/cart/love', (req, res) => {
const { productId } = req.body;
if (!productId || !shoppingCart[productId]) {
return res.status(400).json({ error: 'Product not found in cart' });
}
shoppingCart[productId].loveCount += 1;
res.json({ message: 'Item loved', item: shoppingCart[productId] });
});
app.delete('/api/cart/remove', (req, res) => {
const { productId } = req.body;
if (!productId || !shoppingCart[productId]) {
return res.status(400).json({ error: 'Product not found in cart' });
}
delete shoppingCart[productId];
res.json({ message: 'Item removed', cart: shoppingCart });
});
app.get('/api/cart', (req, res) => {
res.json({ cart: shoppingCart });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
let shoppingCart = {};
function addOrUpdateProduct(productId, productInfo) {
if (shoppingCart[productId]) {
shoppingCart[productId].quantity += 1;
} else {
shoppingCart[productId] = {
productId,
name: productInfo.name,
price: productInfo.price,
quantity: 1,
loveCount: 0
};
}
return shoppingCart[productId];
}
app.post('/api/cart/fetch-and-add', async (req, res) => {
const { productId } = req.body;
if (!productId) {
return res.status(400).json({ error: 'Product ID is required' });
}
try {
// External API call to fetch product details and initial love rating
const externalResponse = await axios.get(`https://api.externalproduct.com/items/${productId}`);
const productData = externalResponse.data;
const cartItem = addOrUpdateProduct(productId, {
name: productData.name,
price: productData.price
});
// Using external love rating if available
cartItem.loveCount = productData.loveRating || cartItem.loveCount;
res.json({ message: 'Product added to cart with external data', item: cartItem });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch external product data' });
}
});
app.get('/api/cart/sync-loves', async (req, res) => {
const productIds = Object.keys(shoppingCart);
try {
const syncResults = await Promise.all(productIds.map(async (id) => {
const response = await axios.get(`https://api.externalproduct.com/items/${id}`);
shoppingCart[id].loveCount = response.data.loveRating || shoppingCart[id].loveCount;
return { productId: id, loveCount: shoppingCart[id].loveCount };
}));
res.json({ message: 'Love counts synchronized', updates: syncResults });
} catch (error) {
res.status(500).json({ error: 'Error synchronizing love counts' });
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
let shoppingCart = {};
app.post('/api/cart/finalize', async (req, res) => {
const { userId } = req.body;
if (!userId) return res.status(400).json({ error: 'User ID required' });
const cartItems = Object.values(shoppingCart);
if (cartItems.length === 0) return res.status(400).json({ error: 'Cart is empty' });
try {
// Validate item availability via external inventory API
const inventoryResults = await Promise.all(cartItems.map(async item => {
const { data } = await axios.get(`https://inventory.example.com/api/check/${item.productId}`);
return { ...item, available: data.available };
}));
const unavailable = inventoryResults.filter(item => !item.available);
if (unavailable.length > 0) {
return res.status(409).json({ error: 'Some items are unavailable', items: unavailable });
}
// Apply discount for items with high love count (threshold: 5)
const discountApplied = await Promise.all(inventoryResults.map(async item => {
if (item.loveCount >= 5) {
const { data } = await axios.post('https://discount.example.com/api/apply', {
productId: item.productId,
userId: userId,
basePrice: item.price
});
return { ...item, discount: data.discount };
}
return item;
}));
// Calculate order total and create order summary
const orderTotal = discountApplied.reduce((total, item) => {
const priceAfterDiscount = item.price - (item.discount || 0);
return total + (priceAfterDiscount \* item.quantity);
}, 0);
const order = {
orderId: `ORD-${Date.now()}`,
userId,
items: discountApplied,
total: orderTotal
};
// Clear the shopping cart after order is finalized
shoppingCart = {};
res.json({ message: 'Order finalized successfully', order });
} catch (error) {
res.status(500).json({ error: 'Checkout failed', details: error.message });
}
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Checkout service running on port ${PORT}`));
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Understanding the Project and AI Code Generators
Defining Your Application Requirements
Choosing the Right AI Code Generator
Planning the Integration of AI-Generated Code
Generating and Reviewing Code
Integrating the Code Into Your Project
Example of an AI-Generated Shopping Cart Function
def add_to_cart(cart, product\_id, quantity):
"""
Adds a product to the shopping cart.
Parameters:
cart (dict): The current shopping cart.
product\_id (str): Unique identifier of the product.
quantity (int): Number of the product to add.
Returns:
dict: Updated shopping cart.
"""
if product\_id in cart:
cart[product\_id] += quantity
else:
cart[product\_id] = quantity
return cart
Example usage
shopping_cart = {}
shopping_cart = add_to_cart(shopping_cart, "SKU1234", 2)
print(shopping_cart)
Testing and Debugging the Integrated Code
Implementing Security Best Practices
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.