E-Commerce Application using Express – Sessions & Cookies
Aim
To build a simple E-Commerce application using Node.js and Express.js that demonstrates the management of Sessions and Cookies for handling shopping cart data and user information.
Software Requirements
- Node.js
- VS Code
- Web Browser
Open the project folder in VS Code. The finished project looks like this:
ecommerce-app/
│
├── server.js
├── package.json
│
└── public/
└── index.htmlnpm init -y
npm install express express-session cookie-parserThis file sets up Express, configures sessions and cookies, defines product data, and creates routes for cart operations and cookie management.
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const app = express();
const PORT = 5000;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static('public'));
// Session Configuration
app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 1000 * 60 * 30 } // 30 minutes
}));
// Products
const products = [
{ id: 1, name: 'Wireless Headphones', price: 1999 },
{ id: 2, name: 'Smart Watch', price: 2999 },
{ id: 3, name: 'Bluetooth Speaker', price: 1499 },
{ id: 4, name: 'USB-C Charger', price: 799 },
{ id: 5, name: 'Laptop Stand', price: 1199 }
];
// ========== ROUTES ==========
// Get all products
app.get('/products', (req, res) => {
res.json(products);
});
// Add to Cart (using Session)
app.post('/add-to-cart', (req, res) => {
const productId = Number(req.body.id);
const product = products.find(p => p.id === productId);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
if (!req.session.cart) {
req.session.cart = [];
}
const existingItem = req.session.cart.find(item => item.id === productId);
if (existingItem) {
existingItem.qty += 1;
} else {
req.session.cart.push({
id: product.id,
name: product.name,
price: product.price,
qty: 1
});
}
res.json({
message: 'Added to cart',
sessionId: req.sessionID,
cart: req.session.cart
});
});
// View Cart
app.get('/cart', (req, res) => {
const cart = req.session.cart || [];
res.json({
message: 'Current cart',
sessionId: req.sessionID,
cart: cart,
totalItems: cart.reduce((sum, item) => sum + item.qty, 0)
});
});
// Clear Cart
app.get('/clear-cart', (req, res) => {
req.session.cart = [];
res.json({
message: 'Cart cleared successfully',
sessionId: req.sessionID,
cart: []
});
});
// Set Cookie
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'StudentUser', {
maxAge: 1000 * 60 * 30,
httpOnly: true
});
res.json({ message: 'Cookie set successfully' });
});
// Get Cookie
app.get('/get-cookie', (req, res) => {
const username = req.cookies.username;
if (username) {
res.json({
message: 'Cookie found',
username: username
});
} else {
res.json({ message: 'No cookie found' });
}
});
// Delete Cookie
app.get('/delete-cookie', (req, res) => {
res.clearCookie('username');
res.json({ message: 'Cookie deleted successfully' });
});
// Session Info
app.get('/session-info', (req, res) => {
res.json({
sessionId: req.sessionID,
cart: req.session.cart || [],
cookies: req.cookies
});
});
// Start Server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});The front-end page displays products, allows adding items to cart, and provides buttons to manage sessions and cookies.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple E-Commerce Application</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #f4f6f9;
color: #1a1a2e;
line-height: 1.5;
padding: 40px 20px;
}
.container {
max-width: 720px;
margin: 0 auto;
}
header {
text-align: center;
margin-bottom: 40px;
}
header h1 {
font-size: 28px;
font-weight: 700;
color: #1a1a2e;
margin-bottom: 6px;
}
header p {
font-size: 15px;
color: #6b7280;
}
.card {
background: #ffffff;
border-radius: 16px;
padding: 28px;
margin-bottom: 24px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
}
.card h2 {
font-size: 18px;
font-weight: 600;
margin-bottom: 20px;
color: #1a1a2e;
}
.product {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 0;
border-bottom: 1px solid #f0f0f0;
}
.product:last-child {
border-bottom: none;
}
.product-info {
font-size: 15px;
color: #1a1a2e;
}
.product-info span {
color: #6b7280;
}
.btn {
background-color: #1e293b;
color: white;
border: none;
padding: 9px 18px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
}
.btn:hover {
background-color: #0f172a;
}
.btn-danger {
background-color: #ef4444;
}
.btn-danger:hover {
background-color: #dc2626;
}
.btn-group {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
#result {
background-color: #f8fafc;
border-radius: 10px;
padding: 18px;
font-family: "SF Mono", "Consolas", "Courier New", monospace;
font-size: 13.5px;
color: #1e293b;
white-space: pre-wrap;
line-height: 1.6;
min-height: 80px;
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Simple E-Commerce Application</h1>
<p>Demonstrating Sessions & Cookies</p>
</header>
<div class="card">
<h2>Products</h2>
<div id="products"></div>
</div>
<div class="card">
<h2>Cart & Session Operations</h2>
<div class="btn-group">
<button class="btn" onclick="viewCart()">View Cart</button>
<button class="btn btn-danger" onclick="clearCart()">Clear Cart</button>
<button class="btn" onclick="sessionInfo()">Session Info</button>
</div>
</div>
<div class="card">
<h2>Cookie Operations</h2>
<div class="btn-group">
<button class="btn" onclick="setCookie()">Set Cookie</button>
<button class="btn" onclick="getCookie()">Get Cookie</button>
<button class="btn btn-danger" onclick="deleteCookie()">Delete Cookie</button>
</div>
</div>
<div class="card">
<h2>Result</h2>
<pre id="result">Click any button to see output...</pre>
</div>
</div>
<script>
const productsList = [
{ id: 1, name: "Wireless Headphones", price: 1999 },
{ id: 2, name: "Smart Watch", price: 2999 },
{ id: 3, name: "Bluetooth Speaker", price: 1499 },
{ id: 4, name: "USB-C Charger", price: 799 },
{ id: 5, name: "Laptop Stand", price: 1199 }
];
function loadProducts() {
const div = document.getElementById('products');
div.innerHTML = '';
productsList.forEach(p => {
div.innerHTML += `
<div class="product">
<div class="product-info">
${p.name} <span>— ₹${p.price}</span>
</div>
<button class="btn" onclick="addToCart(${p.id})">Add to Cart</button>
</div>
`;
});
}
async function addToCart(id) {
const res = await fetch('/add-to-cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
});
const data = await res.json();
showResult(data);
}
async function viewCart() {
const res = await fetch('/cart');
const data = await res.json();
showResult(data);
}
async function clearCart() {
const res = await fetch('/clear-cart');
const data = await res.json();
showResult(data);
}
async function sessionInfo() {
const res = await fetch('/session-info');
const data = await res.json();
showResult(data);
}
async function setCookie() {
const res = await fetch('/set-cookie');
const data = await res.json();
showResult(data);
}
async function getCookie() {
const res = await fetch('/get-cookie');
const data = await res.json();
showResult(data);
}
async function deleteCookie() {
const res = await fetch('/delete-cookie');
const data = await res.json();
showResult(data);
}
function showResult(data) {
document.getElementById('result').innerText = JSON.stringify(data, null, 2);
}
loadProducts();
</script>
</body>
</html>In the project folder run:
node server.jsYou should see:
In your browser, go to:
Do not open index.html directly from the file system.
The page must be loaded through the Express server so that session and cookie
requests work correctly.
- Click Add to Cart on any product.
- Click View Cart to see items stored in the session.
- Click Session Info to view Session ID and cart data.
- Click Clear Cart to empty the session cart.
- Click Set Cookie, then Get Cookie to test cookies.
- Click Delete Cookie to remove the cookie.
What Students Will Learn
| Feature | Concept Demonstrated |
|---|---|
| Add to Cart | Storing data in Session |
| View Cart | Reading data from Session |
| Clear Cart | Modifying / Clearing Session data |
| Set Cookie | Creating a Cookie |
| Get Cookie | Reading a Cookie |
| Delete Cookie | Removing a Cookie |
| Session Info | Viewing Session ID + Cart + Cookies |
Result: The E-Commerce application successfully demonstrates the management of Sessions and Cookies using Express.js. Product cart data is stored in the session, and user information is managed using cookies.






0 Ravula Kartheek:
Post a Comment