Skip to content

Latest commit

Β 

History

107 Commits

Folders and files

Repository files navigation

Backend Template

A production-ready Node.js/Express backend template with TypeScript, MongoDB, Redis, MeiliSearch, Socket.io, and Stripe integration. Built with best practices for scalability, maintainability, and performance.

πŸš€ Features

  • Authentication & Authorization - JWT with refresh tokens & OAuth (Google, Facebook)
  • Database - MongoDB with Mongoose ORM and validation
  • Full-Text Search - MeiliSearch for advanced product search capabilities
  • Real-Time Communication - Socket.io for live updates and notifications
  • Payment Processing - Stripe integration with webhook support
  • Job Queue - BullMQ with Redis for async task processing
  • Caching - Redis for session management and data caching
  • File Uploads - Multer for secure file handling
  • Email Service - Nodemailer for transactional emails
  • Push Notifications - Firebase Cloud Messaging
  • Structured Logging - Winston with daily log rotation
  • Input Validation - Zod schema validation for type safety
  • Security - CORS, bcrypt hashing, JWT tokens, rate limiting ready

πŸ“‹ Prerequisites

  • Node.js 16 or higher
  • MongoDB 4.0+ (local or Atlas)
  • Redis 6.0+
  • MeiliSearch (for full-text search)
  • Docker & Docker Compose (optional, for containerization)

πŸ› οΈ Tech Stack

Layer Technology
Runtime Node.js 16+
Framework Express.js
Language TypeScript
Database MongoDB + Mongoose
Search MeiliSearch
Cache/Queue Redis + BullMQ
Authentication JWT + bcrypt + Passport
Payment Stripe API
Real-Time Socket.io
File Upload Multer
Emails Nodemailer
Notifications Firebase Admin SDK
Logging Winston
Validation Zod
Testing Jest + Supertest

πŸ“¦ Project Structure

my_backend_template/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.ts                      # Express app initialization
β”‚   β”œβ”€β”€ server.ts                   # Server entry point
β”‚   β”œβ”€β”€ config/                     # Configuration modules
β”‚   β”‚   β”œβ”€β”€ database.ts             # MongoDB connection
β”‚   β”‚   β”œβ”€β”€ redis.ts                # Redis client setup
β”‚   β”‚   β”œβ”€β”€ logger.ts               # Winston logger config
β”‚   β”‚   β”œβ”€β”€ env.ts                  # Environment variables
β”‚   β”‚   └── constants.ts            # App constants
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ modules/                # Feature modules
β”‚   β”‚   β”‚   β”œβ”€β”€ auth/               # Authentication
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth.service.ts
β”‚   β”‚   β”‚   β”‚   └── auth.route.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ users/              # User management
β”‚   β”‚   β”‚   β”œβ”€β”€ products/           # Product catalog
β”‚   β”‚   β”‚   β”œβ”€β”€ bookings/           # Booking system
β”‚   β”‚   β”‚   β”œβ”€β”€ payments/           # Payment handling
β”‚   β”‚   β”‚   └── notifications/      # Notifications
β”‚   β”‚   β”œβ”€β”€ middlewares/            # Express middlewares
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.middleware.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ errorHandler.ts
β”‚   β”‚   β”‚   └── validation.middleware.ts
β”‚   β”‚   β”œβ”€β”€ routes/                 # API routes
β”‚   β”‚   └── builders/               # Query builders
β”‚   β”œβ”€β”€ helpers/                    # Utility functions
β”‚   β”œβ”€β”€ services/                   # Business logic
β”‚   β”œβ”€β”€ types/                      # TypeScript types & interfaces
β”‚   β”œβ”€β”€ errors/                     # Custom error classes
β”‚   β”œβ”€β”€ enums/                      # Enumerations
β”‚   └── workers/                    # Background job workers
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ user/
β”‚   β”œβ”€β”€ login/
β”‚   └── setup.ts                    # Test setup
β”œβ”€β”€ .env.example                    # Environment template
β”œβ”€β”€ jest.config.js                  # Jest configuration
β”œβ”€β”€ tsconfig.json                   # TypeScript config
β”œβ”€β”€ package.json
└── README.md

πŸš€ Quick Start

1. Clone Repository & Install Dependencies

git clone https://github.com/iamRazzakk/server.git
cd server
npm install

2. Environment Configuration

Create .env file from template:

cp .env.example .env

Edit .env with your values:

# === Server Configuration ===
PORT=5000
NODE_ENV=development

# === Database ===
MONGODB_URI=mongodb://localhost:27017/my_backend_db

# === JWT Authentication ===
JWT_SECRET=your_super_secret_jwt_key_here
JWT_EXPIRE=7d
JWT_REFRESH_SECRET=your_refresh_token_secret
JWT_REFRESH_EXPIRE=30d

# === Redis ===
REDIS_URL=redis://localhost:6379

# === MeiliSearch ===
MEILI_HOST=http://localhost:7700
MEILI_MASTER_KEY=your_master_key
MEILI_INDEX=products

# === Stripe Payment ===
STRIPE_SECRET_KEY=sk_test_your_key
STRIPE_WEBHOOK_SECRET=whsec_your_secret

# === Firebase ===
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_PRIVATE_KEY=your_private_key
FIREBASE_CLIENT_EMAIL=your_email@firebase.gserviceaccount.com

# === Email Service ===
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASS=your_app_password

# === OAuth (Optional) ===
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret

3. Start Services with Docker Compose

docker-compose up -d

This starts:

  • Redis (port 6379)
  • MeiliSearch (port 7700)
  • MongoDB (port 27017) - if configured

4. Run Development Server

npm run dev

Server starts at http://localhost:5000

5. Run Tests

npm run test
npm run test:watch

6. Build for Production

npm run build
npm start

πŸ“š API Documentation

Authentication Endpoints

POST   /api/v1/auth/register     - Register new user
POST   /api/v1/auth/login        - Login user
POST   /api/v1/auth/logout       - Logout user
POST   /api/v1/auth/refresh      - Refresh JWT token
POST   /api/v1/auth/forgot-password - Reset password

User Endpoints

GET    /api/v1/user              - Get current user profile
GET    /api/v1/user/:id          - Get user by ID
PUT    /api/v1/user/:id          - Update user profile
DELETE /api/v1/user/:id          - Delete user account

Product Endpoints

GET    /api/v1/products          - Get all products (paginated)
GET    /api/v1/products/:id      - Get product details
POST   /api/v1/products          - Create product (admin)
PUT    /api/v1/products/:id      - Update product (admin)
DELETE /api/v1/products/:id      - Delete product (admin)
GET    /api/v1/products/search?q=query - Full-text search

Payment Endpoints

POST   /api/v1/payments          - Create payment intent
POST   /api/v1/payments/webhook  - Stripe webhook handler
GET    /api/v1/payments/:id      - Get payment status

πŸ” Search Implementation

Full-text search using MeiliSearch:

import { searchProducts } from './app/modules/products/product.service';

// Search with filters
const results = await searchProducts({
  query: 'laptop',
  page: 1,
  limit: 20,
  filters: { price: { min: 100, max: 2000 } }
});

πŸ” Authentication Flow

JWT Strategy

  1. User logs in with credentials
  2. Server validates and generates JWT + Refresh Token
  3. Client stores JWT in memory/localStorage
  4. JWT included in Authorization header
  5. Token expires after 7 days (configurable)
  6. Refresh token renews JWT without re-login

OAuth Support

  • Google Login - One-click authentication
  • Facebook Login - Social profile import
  • Auto-creates user on first login

πŸ’³ Payment Processing

Stripe integration features:

// Create payment intent
const paymentIntent = await stripe.paymentIntents.create({
  amount: 5000, // $50.00
  currency: 'usd',
  payment_method_types: ['card']
});

// Handle webhook
app.post('/stripe-webhook', express.raw({type: 'application/json'}), 
  handleStripeWebhook
);

πŸ“§ Email Service

Send transactional emails:

import { sendEmail } from './helpers/email.helper';

await sendEmail({
  to: 'user@example.com',
  subject: 'Welcome to our platform',
  template: 'welcome',
  data: { userName: 'John' }
});

πŸ“² Real-Time Features

Socket.io for live communication:

// Server-side
io.on('connection', (socket) => {
  socket.on('notify-user', (data) => {
    io.to(data.userId).emit('notification', data);
  });
});

// Client-side
socket.emit('notify-user', { userId: '123', message: 'Hello' });
socket.on('notification', (data) => console.log(data));

πŸ—„οΈ Database Schema

MongoDB Collections

users

{
  _id: ObjectId,
  name: String,
  email: String (unique),
  password: String (hashed),
  role: "USER" | "ADMIN" | "SUPER_ADMIN",
  avatar: String,
  contact: String,
  isVerified: Boolean,
  createdAt: Date,
  updatedAt: Date
}

products

{
  _id: ObjectId,
  name: String,
  description: String,
  price: Number,
  category: String,
  stock: Number,
  images: [String],
  ratings: Number,
  seller: ObjectId (ref: users),
  createdAt: Date,
  updatedAt: Date
}

payments

{
  _id: ObjectId,
  user: ObjectId (ref: users),
  amount: Number,
  currency: String,
  status: "PENDING" | "SUCCESS" | "FAILED",
  stripeId: String,
  metadata: Object,
  createdAt: Date
}

βœ… Best Practices Implemented

  • βœ… Modular Architecture - Organized by feature
  • βœ… TypeScript - Full type safety
  • βœ… Error Handling - Custom error classes with proper HTTP status codes
  • βœ… Validation - Zod schemas for all inputs
  • βœ… Logging - Structured logging with Winston
  • βœ… Security - CORS, bcrypt, helmet, environment variables
  • βœ… Testing - Jest unit & integration tests
  • βœ… Code Quality - ESLint and Prettier configured
  • βœ… Scalability - Redis caching, job queues, connection pooling
  • βœ… Documentation - JSDoc comments and API docs

πŸ§ͺ Testing

Run tests:

# Run all tests
npm run test

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage

πŸ› Error Handling

All errors follow standard format:

throw new ApiError(
  StatusCodes.BAD_REQUEST, 
  "Validation failed",
  { field: "email", message: "Invalid email" }
);

Response:

{
  "success": false,
  "statusCode": 400,
  "message": "Validation failed",
  "errors": [...]
}

πŸ“ Logging

Logs are stored in logs/ directory:

logs/
β”œβ”€β”€ success/
β”‚   └── YYYY-MM-DD.log
└── error/
    └── YYYY-MM-DD.log

Access logs:

tail -f logs/error/2024-02-17.log

πŸ“¦ Available Scripts

npm run dev           # Start dev server with hot reload
npm run build         # Compile TypeScript to JavaScript
npm start             # Start production server
npm run test          # Run test suite
npm run test:watch   # Run tests in watch mode
npm run lint          # Run ESLint
npm run format        # Format code with Prettier
npm run seed          # Seed database with sample data

🀝 Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“„ License

ISC

πŸ‘€ Author

Abdur Razzak

πŸ“ž Support & Feedback


Built with ❀️ | Ready for Production πŸš€

About

A production-ready Node.js/Express backend template with TypeScript, MongoDB, Redis, MeiliSearch, Socket.io, and Stripe integration. Built with best practices for scalability, maintainability, and performance.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages