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.
- 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
- 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)
| 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 |
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
git clone https://github.com/iamRazzakk/server.git
cd server
npm installCreate .env file from template:
cp .env.example .envEdit .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_secretdocker-compose up -dThis starts:
- Redis (port 6379)
- MeiliSearch (port 7700)
- MongoDB (port 27017) - if configured
npm run devServer starts at http://localhost:5000
npm run test
npm run test:watchnpm run build
npm startPOST /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
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
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
POST /api/v1/payments - Create payment intent
POST /api/v1/payments/webhook - Stripe webhook handler
GET /api/v1/payments/:id - Get payment status
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 } }
});- User logs in with credentials
- Server validates and generates JWT + Refresh Token
- Client stores JWT in memory/localStorage
- JWT included in Authorization header
- Token expires after 7 days (configurable)
- Refresh token renews JWT without re-login
- Google Login - One-click authentication
- Facebook Login - Social profile import
- Auto-creates user on first login
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
);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' }
});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));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
}- β 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
Run tests:
# Run all tests
npm run test
# Watch mode
npm run test:watch
# Coverage report
npm run test:coverageAll 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": [...]
}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.lognpm 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- Fork the repository
- Create feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
ISC
Abdur Razzak
- π§ Email: mdabdurrazzakrakib290@gmail.com
- π Issues: GitHub Issues
- π¬ Discussions: GitHub Discussions
Built with β€οΈ | Ready for Production π