You've inherited a small e-commerce backend built with Express. It exposes
endpoints for user authentication, browsing products, managing a shopping
cart, and placing orders — but the checkout flow has been misbehaving in
QA, and a few other rough edges have been reported.
Your job is not to redesign anything. The architecture, routes, and
response shapes are all intentional. Find and fix the bugs so the existing
test suite (app.test.js) passes.
Project structure
index.js — starts the server (do not modify)
constants.js — shared config values (JWT secret, etc.)
db.js — in-memory data store (users, products, carts, orders)
middleware/auth.js — JWT-based authentication middleware
app.js — the Express app: routes for auth, products, cart, and orders
app.test.js — the test suite your solution must satisfy (do not modify)
Data model
Product
{ "id": 1, "name": "Wireless Mouse", "price": 25.99, "stock": 10 }
Cart item (stored per user)
{ "productId": 1, "quantity": 2 }
Order
{
"id": 1,
"userId": 1,
"items": [{ "productId": 2, "name": "Mechanical Keyboard", "quantity": 2, "price": 79.99 }],
"total": 159.98,
"createdAt": "2026-08-21T10:00:00.000Z"
}
Endpoints
Auth
POST /auth/register — { username, password } → 201 with { id, username }. 400 if fields are missing, 409 if the username is taken.
POST /auth/login — { username, password } → 200 with { token }. 401 on bad credentials.
Products
GET /products → 200 with { products }.
GET /products/:id → 200 with the product, or 404 if it doesn't exist.
Cart (requires Authorization: Bearer <token>)
GET /cart → 200 with { cart } for the authenticated user only.
POST /cart — { productId, quantity } → 201 with the updated cart. Adding a product already in the cart should increase its quantity, not overwrite it. 404 if the product doesn't exist.
DELETE /cart/:productId → 200 with the updated cart, or 404 if the item isn't in the cart.
Orders (requires Authorization: Bearer <token>)
POST /orders — creates an order from the authenticated user's current cart, decrements product stock, and clears the cart. 400 if the cart is empty. An order must never be created if it would take any product's stock below zero.
GET /orders → 200 with { orders } for the authenticated user only.
Notes
- Carts and orders are scoped per user — one user should never see or affect another user's cart.
- Passwords must never be returned in API responses, and must be verified securely, not compared as plain strings.
- Order totals must reflect quantity, not just unit price.
- Everything you need is already installed in the environment (
express, bcrypt, jsonwebtoken, jest, supertest). No package.json changes needed.