Skip to content
advancedPhase 97 · Production-Ready

Production E-Commerce Platform

Add testing (unit, integration, e2e), Docker containerization, CI/CD pipelines, security hardening, rate limiting, and monitoring dashboards.

6h 40m
0 problems
Topic Progress0%

Project Overview

Production E-Commerce Platform

Take e-commerce from Level 3 to production-ready.

Production Requirements

Area Requirement
Testing Unit, integration, API tests
Security Rate limiting, validation, XSS prevention
Docker Multi-container setup
CI/CD Automated testing and deployment
Monitoring Health checks, error tracking, logging
Performance Redis caching, DB optimization

Architecture — What Goes Where and Why

Project Architecture

Before writing any code, let's understand what files we need and where they go. Think of this like a blueprint for a house — you don't start building without a plan.

The File Tree

Every project needs a folder structure. Here is ours:

├── server.js
├── database.js
├── middleware/security.js
├── middleware/cache.js
├── routes/products.js
├── routes/orders.js
├── monitoring/health.js

What Each File Does

Let me explain each file like you're 5 years old:

server.js — Production Express server

Full e-commerce API with security, caching, monitoring.

database.js — PostgreSQL with pooling

Connection pooling, read replicas, migrations.

middleware/security.js — Security middleware

Rate limiting, CORS, helmet, input sanitization.

middleware/cache.js — Redis caching

Cache product listings and frequently accessed data.

routes/products.js — Product API

Full CRUD with image upload, search, and pagination.

routes/orders.js — Order processing

Checkout, payment integration, order tracking.

monitoring/health.js — Health checks

Endpoints for load balancers and monitoring tools.

Why This Structure?

You might wonder: why use folders at all? Why not put everything in one place?

Because as projects grow, you might have:

  • Multiple CSS files
  • Many JavaScript files
  • Images, fonts, and other assets

If they're all in one folder, it's chaos. Folders keep things organized.

// BAD — everything in one folder
index.html
styles.css
main.css
dark.css
app.js
utils.js
helper.js

// GOOD — organized in folders
index.html
css/
  styles.css
  main.css
js/
  app.js
  utils.js

The Golden Rule

When you start a project, ALWAYS:

  1. Create the folder structure FIRST
  2. Then fill in the files one by one
  3. Never write everything in one giant file

This is how professional developers work. Always.

Step 1 — Project Setup (Creating the Empty House)

Setting Up the Project

We are going to create an empty project from scratch. This is the exact process professional developers use every single day.

Open Your Terminal

Your terminal (also called "command line" or "console") is where you type commands to talk to your computer.

  • Mac: Open "Terminal" app
  • Windows: Open "PowerShell" or "Command Prompt"
  • VS Code: Press Ctrl+` (backtick) to open the built-in terminal

Step-by-Step Commands

Type each of these commands, one at a time, pressing Enter after each:

mkdir prod-ecommerce && cd prod-ecommerce && git init && npm init -y && npm install express pg redis helmet cors && mkdir middleware routes monitoring

What Just Happened?

Let me explain each command like you're 5:

mkdir [folder] — "Make a new box." This creates a folder on your computer.

cd [folder] — "Go inside the box." Now when you type commands, they happen inside this folder.

git init — "Start keeping a diary." Git will now track every change you make. If you break something, you can go back in time.

npm init -y — "Create an ID card for this project." It creates package.json with default settings. The -y means "yes to all questions."

touch [file] — "Create an empty file." Think of it as a blank piece of paper.

Verify It Worked

Type this command to see your files:

ls -la

The .gitignore File

Open .gitignore and add this:

node_modules/
.DS_Store
*.log
.env

Why? Because node_modules can be HUGE — thousands of files. We don't want to save all of them in Git. We can always recreate them with npm install.

Your First Git Commit

Now save everything to Git:

git add .
git commit -m "Initial project setup"

Congratulations! You just set up a project like a real developer.

Step 2 — Building the Core (Step by Step)

Building the Application

Now let's build the application step by step. Follow each step in order.

Build Steps

  1. Set up PostgreSQL with connection pooling
  2. Add Redis for session and product caching
  3. Implement security middleware (helmet, CORS, rate limit)
  4. Build product API with search, filter, pagination
  5. Build cart and checkout flow
  6. Integrate payment processing (Stripe test mode)
  7. Add order tracking and email confirmations
  8. Build health check endpoints
  9. Add structured logging with Winston
  10. Set up error monitoring (Sentry)
  11. Add database migrations
  12. Performance test with Artillery
  13. Deploy with Docker and CI/CD
  14. Commit and deploy

How Each Step Works

Step 1 — Create the entry point

Every application starts with an entry file. This is the file that runs first when someone opens your app.

Think of it like the front door of a house. Everything starts when you walk through it.

Step 2 — Set up the structure

Before writing features, we set up the basic layout. This is like putting up the walls before painting them.

Step 3 — Add the main functionality

Now we add what makes the app actually DO something. This is the "brain" of the application.

Step 4 — Connect everything

We wire the pieces together. The HTML connects to CSS. The JavaScript connects to HTML. Everything talks to each other.

Step 5 — Test and fix

We try everything, find bugs, and fix them. Real developers spend 30% of their time testing.

Save and Test

After each step, save your files and refresh the browser. If something breaks, check the browser console (F12 → Console tab).

Commit after each major step:

git add .
git commit -m "Describe what you just built"

Pro Tip

Build in small steps. Don't write 100 lines and then test. Write 10 lines, test, fix, then write 10 more. This catches errors early when they're easy to fix.

Testing Strategy

Comprehensive Testing

API Tests

import request from 'supertest';
import app from '../server.js';

describe('Product API', () => {
  it('GET /api/products returns paginated results', async () => {
    const res = await request(app).get('/api/products?page=1&limit=10').expect(200);
    expect(res.body.products).toBeInstanceOf(Array);
    expect(res.body.products.length).toBeLessThanOrEqual(10);
  });

  it('POST /api/products requires auth', async () => {
    await request(app).post('/api/products').send({ name: 'Test' }).expect(401);
  });
});

Unit Tests

describe('calculateOrderTotal', () => {
  it('applies free shipping over $50', () => {
    expect(calculateShipping(60)).toBe(0);
    expect(calculateShipping(30)).toBe(5.99);
  });
});

Security Hardening

Production Security

import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import mongoSanitize from 'express-mongo-sanitize';

app.use(helmet());
app.use('/api/', rateLimit({ windowMs: 15*60*1000, max: 100 }));
app.use('/api/auth/login', rateLimit({ windowMs: 15*60*1000, max: 5 }));
app.use(mongoSanitize());

Input Validation

import Joi from 'joi';
const productSchema = Joi.object({
  name: Joi.string().trim().min(1).max(200).required(),
  price: Joi.number().positive().precision(2).required(),
  sku: Joi.string().pattern(/^[A-Z0-9-]+$/).required()
});

Docker Containerization

Docker Setup

Dockerfile

FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 5000
CMD ["node", "dist/server.js"]

docker-compose.yml

version: '3.8'
services:
  api:
    build: .
    ports: ["5000:5000"]
    environment:
      - MONGODB_URI=mongodb://mongo:27017/ecommerce
      - REDIS_URL=redis://redis:6379
    depends_on: [mongo, redis]
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:5000/health"]
      interval: 30s
  mongo:
    image: mongo:6
    volumes: [mongo-data:/data/db]
  redis:
    image: redis:7-alpine
    volumes: [redis-data:/data]
volumes:
  mongo-data:
  redis-data:

Health Check

app.get('/health', async (req, res) => {
  const checks = { api: 'ok', database: 'unknown', redis: 'unknown' };
  try { await mongoose.connection.db.admin().ping(); checks.database = 'ok'; } catch {}
  try { await redis.ping(); checks.redis = 'ok'; } catch {}
  const healthy = Object.values(checks).every(v => v === 'ok');
  res.status(healthy ? 200 : 503).json(checks);
});

Common Mistakes (What Goes Wrong)

Mistakes Everyone Makes

Every developer makes these mistakes. Knowing them ahead of time saves hours of debugging.

Mistake 1: Forgetting to Connect Files

<!-- WRONG — CSS is not linked, page looks ugly -->
<link rel="stylesheet" href="style.css">

<!-- RIGHT — file path matches actual location -->
<link rel="stylesheet" href="css/styles.css">

How to check: Right-click the page → Inspect → Network tab → look for red (failed) resources.

Mistake 2: JavaScript Before HTML

<!-- WRONG — JavaScript runs before HTML exists -->
<script src="app.js"></script>
<body>...</body>

<!-- RIGHT — JavaScript runs after HTML loads -->
<body>...</body>
<script src="app.js"></script>

Mistake 3: Not Using preventDefault()

// WRONG — page reloads when you submit
form.addEventListener('submit', () => {
  // This code runs, but then the page reloads!
});

// RIGHT — preventDefault stops the reload
form.addEventListener('submit', (e) => {
  e.preventDefault(); // Now the page doesn't reload
});

Mistake 4: Modifying State Without Re-rendering

// WRONG — changes data but screen stays the same
todos.push(newTodo);

// RIGHT — always update the screen after changing data
todos.push(newTodo);
render(); // Now the screen shows the new todo

Mistake 5: Not Handling Empty Input

// WRONG — adds empty tasks
addTodo(""); // Adds a blank todo

// RIGHT — check for empty input
if (text.trim()) {
  addTodo(text);
}

Mistake 6: Ignoring Errors

How to check for errors:

  1. Press F12 in your browser
  2. Click "Console" tab
  3. Look for red text
  4. Click on it to see what went wrong

If you see red text, DON'T IGNORE IT. That's the computer telling you something is broken.

Debugging Checklist

When something doesn't work:

  1. Check the console — F12 → Console (red text = error)
  2. Check the Network — F12 → Network (red lines = failed requests)
  3. Check file paths — Are CSS/JS files in the right folder?
  4. Check spelling — Typos in IDs, class names, function names
  5. Check the basics — Is the server running? Is the URL correct?

The 5-Minute Rule

If you've been stuck for 5 minutes:

  1. Stop
  2. Re-read the error message
  3. Search the error on Google/Stack Overflow
  4. If still stuck, ask for help

Don't waste hours on something that might be a simple typo.

What You Just Learned

Summary — Skills You Now Have

Technical Skills

  1. Project Structure — You know how to organize files in folders
  2. Git — You can initialize, add, commit, and push
  3. Version Control — You can track changes and go back in time
  4. HTML/CSS/JavaScript — You can build interactive web pages
  5. DOM Manipulation — You can change what's on screen with code
  6. Event Handling — You can respond to clicks, inputs, and other actions
  7. State Management — You can track and update application data
  8. Debugging — You can find and fix errors using browser tools
  9. Testing — You can verify your app works correctly

Thinking Skills

  1. Architecture — You planned the project BEFORE writing code
  2. Problem Solving — You broke a big problem into small steps
  3. Debugging — You systematically found and fixed errors
  4. Documentation — You wrote notes for future you (and other developers)

The Pattern

Every frontend application follows this pattern:

State (data) → Render (draw) → Event (respond) → Update State → Render again

React, Vue, Angular, Svelte — they ALL do this. You just learned the fundamental pattern that powers the entire web.

What's Next?

Look at the next project in the roadmap. Each new project builds on what you learned here. The skills compound — every project makes you a better developer.

Remember: every expert was once a beginner who didn't give up.

Quick Reference

Quick Reference

File Overview

  • server.js: Production Express server
  • database.js: PostgreSQL with pooling
  • middleware/security.js: Security middleware
  • middleware/cache.js: Redis caching
  • routes/products.js: Product API
  • routes/orders.js: Order processing
  • monitoring/health.js: Health checks

Setup Commands

mkdir prod-ecommerce && cd prod-ecommerce && git init && npm init -y && npm install express pg redis helmet cors && mkdir middleware routes monitoring

Common Patterns

// Select an element
const el = document.getElementById('myId');

// Add event listener
el.addEventListener('click', (e) => {
  e.preventDefault();
});

// Update the DOM
el.innerHTML = '<p>New content</p>';
el.textContent = 'Text only';

Debugging

F12 → Console     → Check for errors
F12 → Network     → Check API requests
F12 → Elements    → Inspect HTML/CSS
Ctrl+Shift+M      → Mobile view

Git Commands

git init                  # Start a repo
git add .                 # Stage all changes
git commit -m "message"   # Save changes
git push                  # Upload to GitHub

Quiz

1. Why multi-stage Docker builds?

Question 1 options

Flashcards

Question

What is a health check?

Answer

An endpoint reporting status of dependencies (database, cache, etc.)

Revision Notes

Key Takeaways

  • 1.Production requires comprehensive testing
  • 2.Security must be layered
  • 3.Docker simplifies deployment
  • 4.Health checks enable recovery
  • 5.Structured logging aids debugging

Interview Tips

  • Describe testing strategy
  • Explain Docker builds
  • Discuss security checklist

Cheat Sheet

Production E-Commerce

Security

app.use(helmet());
app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }));

Health Check

app.get('/health', async (req, res) => {
  await mongoose.connection.db.admin().ping();
  await redis.ping();
  res.json({ status: 'ok' });
});