How eslamtaha-dev/mern-ecommerce-backend works
Purpose and entry points
This is a TypeScript/Express REST backend for an e-commerce domain: authentication, catalog/category management, user roles, product images, and orders. server.ts is the long-running Node entry point; it validates environment, connects MongoDB, and listens. app.ts composes the Express application and is also the serverless-compatible handler.
HTTP composition and request boundary
app.ts applies Helmet, CORS, rate limiting, lazy MongoDB connection, route mounting under /api/v1, and terminal error handling. Resource routers define public versus protected endpoints and arrange validation/auth/controller stages:
• routes/auth.route.ts
• routes/product.route.ts
• routes/order.route.ts
Requests are validated before controller/database access through Zod middleware; async failures converge on a centralized HTTP error mapper:
• utils/validate.ts
• utils/errorHandler.ts
• utils/catchAsync.ts
Authentication and authorization
Registration/login create JWTs; user passwords are bcrypt-hashed and hidden by default at the model layer. Protected requests verify the token and reload the user from MongoDB, then role guards enforce admin-only mutations. User role changes preserve the invariant that at least one admin remains.
• controllers/auth.controller.ts
• middlewares/auth.middleware.ts
• models/user.model.ts
• controllers/user.controller.ts
Domain persistence and identifiers
Mongoose models persist to MongoDB/Atlas. Categories and users use ObjectIds. Products and orders additionally expose atomic sequential numeric IDs, generated through a counter collection, which defines their URL lookup contract.
• models/product.model.ts
• models/order.model.ts
• models/category.model.ts
• models/counter.model.ts
• utils/getNextSequence.ts
Catalog and media lifecycle
Product and category controllers implement catalog reads and admin CRUD. Product listing supports pagination, sorting, search, and category filtering. Image-bearing product writes cross a media boundary: Multer accepts image data in memory, Cloudinary receives a stream, and returned URL/public ID are stored with the product. Replaced/deleted assets are cleaned up without making cleanup failure fail the main request.
• controllers/product.controller.ts
• controllers/category.controller.ts
• middlewares/upload.middleware.ts
• utils/cloudinary.ts
Order integrity flow
Authenticated customers submit product references and quantities, not trusted prices. The order controller loads products from MongoDB, derives item pricing and total server-side, then persists the order. Owners can access their orders; admins can list all orders and transition status.
• controllers/order.controller.ts
• models/order.model.ts
• validators/order.validator.ts
Runtime and external infrastructure
Node.js 18+, Express 5, TypeScript, Mongoose, and MongoDB provide the service runtime and data store. Required external services are MongoDB (typically Atlas) and Cloudinary; JWT signing depends on JWT_SECRET. Environment validation fails boot early in the process path, while app.ts’s guarded connection approach supports serverless invocations. Demo data is initialized by scripts/seed.ts.
Main entry points: auth.route.ts API routers · app.ts Express app · product.model.ts Catalog models · user.model.ts User model
Components 18
Runtime
- Node server · Validates environment, connects MongoDB, and listens.
server.ts - Demo data seed · Initializes demo data.
scripts/seed.ts
HTTP API
- Express app · Serverless-compatible app composition with global middleware and error handling.
app.ts - API routers · Public and protected auth, product, and order endpoints under /api/v1.
routes/auth.route.ts - Zod validation · Rejects invalid requests before controllers access data.
utils/validate.ts - Async error mapping · Async failures converge on centralized HTTP error responses.
utils/errorHandler.ts
Identity & Access
- JWT auth guard · Verifies tokens, reloads users, and enforces roles.
middlewares/auth.middleware.ts - Auth controller · Registers and logs in users, issuing JWTs.
controllers/auth.controller.ts - User administration · Manages roles while preserving at least one admin.
controllers/user.controller.ts
Domain Services
- Catalog controllers · Product/category reads and admin CRUD, including filtered product listing.
controllers/product.controller.ts - Image upload · Accepts product images in memory for media writes.
middlewares/upload.middleware.ts - Order controller · Derives prices and totals from persisted products before saving orders.
controllers/order.controller.ts
Persistence
- User model · Hashes passwords and hides them by default.
models/user.model.ts - Catalog models · Products use sequential numeric IDs; categories use ObjectIds.
models/product.model.ts - Order model · Orders expose sequential numeric IDs.
models/order.model.ts - Sequence counter · Atomically allocates product and order numeric IDs.
models/counter.model.ts
External Services
- MongoDB / Atlas
- Cloudinary · Stores product image streams and supports asset cleanup.
Connections 25
- Node server → Express app: starts
- Node server → MongoDB / Atlas: connects at boot
- Express app → MongoDB / Atlas: lazy connection
- Express app → API routers: mounts /api/v1
- Express app → Async error mapping: terminal handler
- API routers → Zod validation: validates
- API routers → JWT auth guard: protects routes
- API routers → Auth controller: auth endpoints
- API routers → Catalog controllers: catalog endpoints
- API routers → Order controller: order endpoints
- JWT auth guard → User model: reloads user
- Auth controller → User model: creates/authenticates
- User administration → User model: updates roles
- Catalog controllers → Image upload: image-bearing writes
- Image upload → Cloudinary: streams images
- Catalog controllers → Catalog models: CRUD and listing
- Catalog models → Sequence counter: allocates product ID
- Order controller → Catalog models: loads trusted products
- Order controller → Order model: persists derived order
- Order model → Sequence counter: allocates order ID
- User model → MongoDB / Atlas: persists
- Catalog models → MongoDB / Atlas: persists
- Order model → MongoDB / Atlas: persists
- Sequence counter → MongoDB / Atlas: persists
- Demo data seed → MongoDB / Atlas: initializes