E‑commerce REST API built with Node.js, Express, and MongoDB (Mongoose). It provides JWT authentication with email verification, role‑based access (user/admin), product catalog CRUD, a persistent shopping cart, and order creation from the cart with transactional stock updates. The codebase follows a clear controller/router/model structure, uses environment‑based configuration, and supports email delivery via Nodemailer (Gmail App Password in prod or Ethereal in dev). Suitable as a clean starter backend for storefronts, admin dashboards, or integrations.
- Requirements: Node.js 18+ and a MongoDB Atlas connection string
- Configure env in
config.env:- DATABASE=mongodb+srv://:@.../...
- DATABASE_PASSWORD=...
- JWT_SECRET=...
- EMAIL=your_gmail@gmail.com (optional)
- EMAIL_PASSWORD=app_password (optional Gmail App Password)
- PORT=3000 (optional)
- Install and run:
- npm install
- npm run dev
server.js— loads env, connects DB, starts serversrc/app.js— Express app and route registrationsrc/controllers/— route handlersuserController.js,productController.js,cartController.js,orderController.js
src/models/— Mongoose modelsuserModel.js,productModel.js,orderModel.js
src/routes/— routers for domainsuserRoute.js,productRoute.js,cartRoute.js,orderRoute.js
src/utils/— helpersauth.js(JWT auth),validateRole.js(admin check),sendEmail.js
- JSON only. Use
Content-Type: application/json. - Auth with
Authorization: Bearer <JWT>for protected endpoints. - Admin-only endpoints use
validateRole('admin').
- POST
/api/v1/auth/register— Register user; returns JWT. Sends verification email. - POST
/api/v1/auth/login— Login; returns JWT. If unverified, resends verification email. - GET
/api/v1/users/me— Get current user (auth). - DELETE
/api/v1/users/delete— Delete current user (auth). - GET
/api/v1/verify/:email— Verify account using tokenized email link.
- GET
/api/v1/products— List products. - GET
/api/v1/products/:id— Get product by id. - POST
/api/v1/products— Create product (auth + admin). - PUT
/api/v1/products/:id— Update product (auth + admin). - DELETE
/api/v1/products/:id— Delete product (auth + admin).
- GET
/api/v1/cart— Get current cart; returns items, subtotal, itemsCount. - POST
/api/v1/cart— Add item:{ productID, quantity }. - PUT
/api/v1/cart— Update quantity:{ productID, quantity }(0 removes item). - DELETE
/api/v1/cart/remove— Remove item:{ productID }. - DELETE
/api/v1/cart— Empty cart.
- POST
/api/v1/orders— Create order from cart. Body:{ shippingAddress, paymentMethod }. - GET
/api/v1/orders— List orders (user sees own; admin sees all). - GET
/api/v1/orders/:id— Get order by id (owner or admin).
- Email sending uses Gmail (EMAIL/EMAIL_PASSWORD) or falls back to Ethereal in dev and prints a preview URL in console.
- DB connection errors and unhandled rejections are logged; server exits on fatal DB errors.
- Timestamps are enabled on models; IDs are MongoDB ObjectIds.
npm run dev— Start with nodemon.npm start— Start server.