A comprehensive e-commerce platform for buying and selling books, built with Node.js, Express.js, and MongoDB. This RESTful API provides complete functionality for user authentication, book management, shopping cart, order processing, and payment integration.
- Node.js (v16 or higher)
- MongoDB (v5 or higher)
- npm or yarn package manager
-
Clone the repository
git clone <repository-url> cd bookBazaar
-
Install dependencies
npm install
-
Environment Configuration
cp .env.example .env
Configure your environment variables (see Environment Variables section)
-
Start MongoDB
# Using Docker Compose (Recommended) docker-compose up -d # Or start MongoDB locally mongod
-
Run the application
# Development mode npm run dev # Production mode npm start
The API will be available at http://localhost:8000
bookBazaar/
βββ src/
β βββ controllers/ # Business logic handlers
β βββ models/ # Database models
β βββ routes/ # API route definitions
β βββ middlewares/ # Custom middleware functions
β βββ validators/ # Input validation schemas
β βββ utils/ # Utility functions
β β βββ cloudinary.js # Image upload service
β β βββ mail.js # Email functionality
β β βββ tokenGeneration.js # JWT token utilities
β βββ db/ # Database configuration
β βββ app.js # Express app configuration
βββ public/ # Static files and uploads
βββ docker-compose.yml # MongoDB container setup
βββ package.json
Create a .env file in the root directory with the following variables:
# Server Configuration
PORT=8000
NODE_ENV=development
CORS_ORIGIN=http://localhost:3000
# Database
MONGODB_URI=mongodb://localhost:27017/bookBazaar
# JWT Configuration
ACCESS_TOKEN_SECRET=your_access_token_secret
REFRESH_TOKEN_SECRET=your_refresh_token_secret
# Cloudinary (Image Storage)
CLOUDINARY_CLOUD_NAME=your_cloudinary_cloud_name
CLOUDINARY_API_KEY=your_cloudinary_api_key
CLOUDINARY_API_SECRET=your_cloudinary_api_secret
# Razorpay (Payment Gateway)
RAZORPAY_KEY_ID=your_razorpay_key_id
RAZORPAY_KEY_SECRET=your_razorpay_key_secret
# Email Configuration (Mailtrap for Development)
MAILTRAP_SMTP_HOST=sandbox.smtp.mailtrap.io
MAILTRAP_SMTP_PORT=2525
MAILTRAP_SMTP_USER=your_mailtrap_username
MAILTRAP_SMTP_PASS=your_mailtrap_password
MAILTRAP_SMTP_SENDEREMAIL=[email protected]POST /api/v1/auth/register
Content-Type: multipart/form-dataRequest Body:
{
"username": "johndoe",
"fullName": "John Doe",
"email": "[email protected]",
"password": "password123",
"role": "user",
"avatar": "file" // Image file
}Response:
{
"success": true,
"message": "User created successfully",
"user": {
"_id": "user_id",
"username": "johndoe",
"fullName": "John Doe",
"email": "[email protected]",
"role": "user",
"avatar": {
"url": "cloudinary_url"
}
}
}POST /api/v1/auth/login
Content-Type: application/jsonRequest Body:
{
"email": "[email protected]",
"password": "password123"
}Response:
{
"success": true,
"message": "User logged in successfully",
"user": {
"fullName": "John Doe",
"username": "johndoe",
"email": "[email protected]",
"role": "user",
"accessToken": "jwt_access_token",
"refreshToken": "jwt_refresh_token"
}
}GET /api/v1/auth/me
Authorization: Bearer <access_token>Response:
{
"success": true,
"message": "Success",
"user": {
"_id": "user_id",
"username": "johndoe",
"fullName": "John Doe",
"email": "[email protected]",
"role": "user",
"avatar": {
"url": "cloudinary_url"
}
}
}POST /api/v1/auth/api-key
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"expiresAt": "2024-12-31T23:59:59.000Z"
}GET /api/v1/books?page=1&limit=10&search=javascript&genre=fiction&author=author_id&sortBy=createdAt&order=descQuery Parameters:
page(optional): Page number (default: 1)limit(optional): Items per page (default: 10, max: 50)search(optional): Search in title and descriptiongenre(optional): Filter by genreauthor(optional): Filter by author IDsortBy(optional): Sort field (default: createdAt)order(optional): Sort order - asc/desc (default: desc)
Response:
{
"success": true,
"message": "Books fetched successfully",
"books": [
{
"_id": "book_id",
"title": "JavaScript: The Good Parts",
"description": "A comprehensive guide to JavaScript",
"author": {
"_id": "author_id",
"username": "author_name",
"fullName": "Author Full Name"
},
"price": 29.99,
"stock": 50,
"genre": "Programming",
"ISBN": "978-0596517748",
"coverImage": "cloudinary_url",
"publisher": "O'Reilly Media",
"publishedDate": "2008-05-15"
}
],
"metadata": {
"totalPages": 5,
"currentPage": 1,
"currentLimit": 10
}
}GET /api/v1/books/:id
Authorization: Bearer <access_token>POST /api/v1/books
Authorization: Bearer <access_token>
Content-Type: multipart/form-dataRequest Body:
{
"title": "New Book Title",
"description": "Book description",
"author": "author_id",
"genre": "Fiction",
"price": 19.99,
"stock": 100,
"ISBN": "978-1234567890",
"publisher": "Publisher Name",
"publishedDate": "2024-01-01",
"coverImage": "file" // Image file
}PUT /api/v1/books/:id
Authorization: Bearer <access_token>
Content-Type: application/jsonDELETE /api/v1/books/:id
Authorization: Bearer <access_token>POST /api/v1/cart
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"book": "book_id",
"quantity": 2
}GET /api/v1/cart?page=1&limit=10
Authorization: Bearer <access_token>PUT /api/v1/cart/:itemId
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"quantity": 3
}DELETE /api/v1/cart/:itemId
Authorization: Bearer <access_token>POST /api/v1/orders
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
}
}Response:
{
"success": true,
"message": "Order created successfully",
"order": {
"_id": "order_id",
"user": "user_id",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"items": [
{
"book": "book_id",
"quantity": 2,
"priceAtPurchase": 29.99
}
],
"totalAmount": 59.98,
"status": "pending",
"createdAt": "2024-01-15T10:30:00.000Z"
}
}Note: An order confirmation email is automatically sent to the user's registered email address upon successful order creation.
GET /api/v1/orders?page=1&limit=10
Authorization: Bearer <access_token>GET /api/v1/orders/:id
Authorization: Bearer <access_token>POST /api/v1/payment/order
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"orderId": "order_id",
"currency": "INR"
}Response:
{
"success": true,
"orderId": "razorpay_order_id",
"amount": 5998,
"currency": "INR"
}POST /api/v1/payment/verify
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"razorpay_order_id": "order_id",
"razorpay_payment_id": "payment_id",
"razorpay_signature": "signature"
}POST /api/v1/books/:bookId/reviews
Authorization: Bearer <access_token>
Content-Type: application/jsonRequest Body:
{
"rating": 5,
"comment": "Excellent book! Highly recommended."
}GET /api/v1/books/:bookId/reviews?page=1&limit=10
Authorization: Bearer <access_token>DELETE /api/v1/books/:bookId/reviews/:id
Authorization: Bearer <access_token>The BookBazaar API includes comprehensive email functionality for order confirmations and customer communication.
- Order Confirmation Emails: Automatically sent when a user places an order
- Professional Email Templates: Using Mailgen for beautiful, responsive email designs
- Mailtrap Integration: Safe email testing environment for development
The system uses Mailtrap for email testing and development:
- Sign up for Mailtrap: Visit mailtrap.io and create an account
- Get SMTP credentials: From your Mailtrap inbox settings
- Configure environment variables: Add the Mailtrap credentials to your
.envfile
When a user successfully places an order, they receive a professional email containing:
- Order Details: Order ID, items purchased, quantities, and prices
- Itemized Table: Clean table showing each book with quantity and price
- Total Amount: Final order total
- Branding: BookBazaar branding and professional styling
- nodemailer: For sending emails via SMTP
- mailgen: For generating beautiful HTML email templates
For production deployment, replace Mailtrap credentials with your production email service:
# Production Email Configuration
MAILTRAP_SMTP_HOST=your_production_smtp_host
MAILTRAP_SMTP_PORT=587
MAILTRAP_SMTP_USER=your_production_email
MAILTRAP_SMTP_PASS=your_production_password
MAILTRAP_SMTP_SENDEREMAIL=[email protected]- Email sending failures are logged but don't affect order creation
- Orders are created successfully even if email delivery fails
- Comprehensive error logging for debugging email issues
- Access Token: Short-lived token for API access (24 hours)
- Refresh Token: Long-lived token for token renewal (7 days)
- Tokens are stored in HTTP-only cookies for security
- user: Can browse books, add to cart, place orders, write reviews
- admin: All user permissions + book management, review moderation
- Generate API keys for programmatic access
- Keys can have custom expiration dates
- Use
X-API-Keyheader for authentication
- Backend: Node.js, Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JWT (JSON Web Tokens)
- File Upload: Multer + Cloudinary
- Payment: Razorpay integration
- Email: Nodemailer + Mailgen for email templates
- Validation: Express Validator
- Security: bcryptjs for password hashing
- Development: Nodemon for hot reloading
-
Build the application
docker build -t bookbazaar-api . -
Run with Docker Compose
docker-compose up -d
- Set
NODE_ENV=production - Configure production MongoDB URI
- Set up proper CORS origins
- Configure production Cloudinary credentials
- Set up Razorpay production keys
- Configure production email service (replace Mailtrap with production SMTP)
All API responses follow a consistent format:
Success Response:
{
"success": true,
"message": "Operation completed successfully",
"data": {
/* response data */
},
"metadata": {
/* pagination info */
}
}Error Response:
{
"success": false,
"message": "Error description",
"error": "Detailed error information"
}The API includes comprehensive error handling for:
- Validation errors (400)
- Authentication errors (401)
- Authorization errors (403)
- Not found errors (404)
- Server errors (500)
- User: User accounts with authentication
- Book: Book catalog with metadata
- CartItem: Shopping cart items
- Order: Order management
- Payment: Payment tracking
- Review: Book reviews and ratings
- ApiKey: API key management
This project is licensed under the ISC License.
Made by β€οΈ Sumit Tomar