Hotel Booking Management System - React, Express.js FullStack MERN Project (including Business-Insights Dashboard)
A comprehensive, production-ready hotel booking platform built with the MERN stack (MongoDB, Express.js, React, Node.js) featuring advanced search, booking management, analytics dashboard, and payment integration.
- Frontend-Live-Demo: https://hotel-mern-booking.vercel.app/
- Backend-Live-Demo: https://hotel-booking-backend.duckdns.org
The Hotel Booking Management System is a full-stack web application that revolutionizes the way hotels are discovered, booked, and managed. Built with modern web technologies, it provides a seamless experience for travelers seeking accommodations and hotel owners managing their properties.
This project serves as a comprehensive hotel booking ecosystem that bridges the gap between travelers and hotel owners. It's designed to be:
- User-Centric: Intuitive interface for travelers to find and book hotels
- Owner-Friendly: Powerful tools for hotel owners to manage their properties
- Data-Driven: Advanced analytics for business insights and decision-making
- Scalable: Built to handle growth from small boutique hotels to large chains
- Discovery: Advanced search with multiple filters (price, location, amenities, ratings)
- Booking: Seamless booking process with secure payment integration
- Management: Easy access to booking history and travel plans
- Trust: Transparent pricing, reviews, and hotel information
- Property Management: Complete CRUD operations for hotel listings
- Booking Management: Real-time booking tracking and guest information
- Analytics: Comprehensive business insights and performance metrics
- Revenue Optimization: Pricing strategies and occupancy analysis
- Learning Resource: Complete MERN stack implementation
- Best Practices: Modern development patterns and architecture
- Production Ready: Deployment strategies and optimization techniques
- Extensible: Modular design for easy feature additions
- Travelers: Individuals and families looking for hotel accommodations
- Hotel Owners: Small to medium hotel proprietors and managers
- Travel Agencies: Organizations managing multiple bookings
- Developers: Learning full-stack development with MERN stack
- Students: Understanding modern web application architecture
- Entrepreneurs: Building similar booking platforms
- Commission-based: Percentage fee on successful bookings
- Subscription: Premium features for hotel owners
- Advertising: Featured hotel listings and promotions
- Analytics: Premium business insights and reporting
- Advanced Search: Multi-criteria filtering and smart recommendations
- Real-time Analytics: Live business insights and performance tracking
- Mobile-First: Responsive design optimized for all devices
- Security: Enterprise-grade authentication and data protection
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β React App β β React Query β β Tailwind CSS β
β (TypeScript) βββββΊβ (State Mgmt) βββββΊβ (Styling) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β React Router β β Shadcn UI β β Vite Build β
β (Navigation) β β (Components) β β (Dev Server) β
βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Express.js β β MongoDB β β JWT Auth β
β (API Server) βββββΊβ (Database) βββββΊβ (Security) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Multer β β Cloudinary β β Stripe β
β (File Upload) β β (Image Mgmt) β β (Payments) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ- Smart Search Algorithm: AI-powered hotel recommendations
- Real-time Availability: Live booking status and instant confirmation
- Advanced Analytics: Predictive insights and business forecasting
- Multi-language Support: Internationalization ready
- Progressive Web App: Offline capabilities and app-like experience
- Dual Authentication: Cookie-based + Authorization header support
- Privacy Compliance: GDPR-ready data handling
- Rate Limiting: Protection against abuse and DDoS
- Input Validation: Comprehensive data sanitization
- Secure Payments: PCI-compliant payment processing
- Responsive Design: Optimized for all screen sizes
- Progressive Enhancement: Works without JavaScript
- Accessibility: WCAG 2.1 AA compliance
- Performance: Sub-2-second page load times
- Offline Support: Cached data for offline browsing
- TypeScript First: Type-safe development throughout
- Component-Driven: Reusable, modular components
- Test-Driven: Comprehensive testing strategy
- Documentation: Self-documenting code with detailed comments
- Lazy Loading: Code splitting and dynamic imports
- Caching Strategy: Intelligent data caching
- Optimization: Bundle size and runtime optimization
- Monitoring: Real-time performance tracking
- Microservices Ready: Modular architecture for scaling
- Database Optimization: Efficient queries and indexing
- CDN Integration: Global content delivery
- Load Balancing: Horizontal scaling capabilities
- β Core booking functionality
- β Hotel management system
- β Basic analytics dashboard
- β Payment integration
- π Advanced search with AI recommendations
- π Real-time chat support
- π Mobile app development
- π Multi-language support
- π Blockchain-based booking verification
- π VR hotel tours
- π AI-powered pricing optimization
- π Integration with travel APIs
- Booking Conversion Rate: Target 15%+ from search to booking
- User Retention: 60%+ return rate within 6 months
- Session Duration: Average 8+ minutes per session
- Mobile Usage: 70%+ of bookings via mobile devices
- Revenue Growth: 25%+ month-over-month growth
- Hotel Partner Growth: 100+ hotels onboarded in first year
- Customer Satisfaction: 4.5+ star rating
- Technical Performance: 99.9% uptime
- Digital Transformation: Modernizing traditional booking processes
- Data Insights: Valuable market intelligence and trends
- Efficiency: Streamlined operations and reduced overhead
- Customer Experience: Enhanced satisfaction and loyalty
- Learning Platform: Comprehensive full-stack development example
- Best Practices: Modern development patterns and techniques
- Portfolio Project: Demonstrates advanced technical skills
- Open Source: Contributing to the developer community
- Features
- Tech Stack
- Project Structure
- Installation & Setup
- Environment Variables
- API Documentation
- Key Components
- Database Schema
- Authentication & Authorization
- Payment Integration
- Search & Filtering
- Analytics Dashboard
- Testing
- Deployment
- Contributing
- License
- Multi-role System: User, Hotel Owner, and Admin roles
- Hotel CRUD Operations: Create, read, update, delete hotel listings
- Image Upload: Cloudinary integration for hotel image management
- Advanced Hotel Details: Location, amenities, policies, contact information
- Hotel Analytics: Booking statistics, revenue tracking, occupancy rates
- Smart Search: Destination-based hotel discovery
- Multi-filter System: Price range, star rating, hotel types, facilities
- Geolocation Support: Location-based search with coordinates
- Sorting Options: Price, rating, distance, relevance
- Pagination: Efficient data loading for large datasets
- Real-time Availability: Check-in/check-out date validation
- Guest Management: Adult and child count tracking
- Payment Integration: Stripe payment processing
- Booking Status: Pending, confirmed, cancelled, completed, refunded
- Booking History: Complete booking logs and analytics
- Real-time Metrics: Revenue, bookings, occupancy rates
- Performance Charts: Revenue trends, booking patterns
- Forecasting: Predictive analytics for business insights
- Hotel Performance: Individual hotel analytics
- User Analytics: User behavior and preferences
- JWT Authentication: Secure token-based authentication
- Role-based Access Control: Granular permissions
- Password Security: bcrypt password hashing
- Rate Limiting: API request throttling
- CORS Protection: Cross-origin resource sharing security
- Responsive Design: Mobile-first approach
- Shadcn UI Components: Modern, accessible UI components
- Tailwind CSS: Utility-first CSS framework
- Dark/Light Mode: Theme customization
- Loading States: Smooth user experience
- Toast Notifications: User feedback system
- React 18.2.0 - Modern UI library with hooks
- TypeScript 5.0.2 - Type-safe JavaScript
- Vite - Fast build tool and dev server
- React Router DOM - Client-side routing
- React Query - Server state management
- Tailwind CSS - Utility-first CSS framework
- Shadcn UI - Modern component library
- Lucide React - Beautiful icons
- React Hook Form - Form validation and handling
- Stripe React - Payment processing
- Node.js - JavaScript runtime
- Express.js - Web application framework
- TypeScript - Type-safe development
- MongoDB - NoSQL database
- Mongoose - MongoDB object modeling
- JWT - JSON Web Token authentication
- bcryptjs - Password hashing
- Multer - File upload handling
- Cloudinary - Cloud image storage
- Stripe - Payment processing
- Swagger - API documentation
- Helmet - Security middleware
- Morgan - HTTP request logger
- CORS - Cross-origin resource sharing
- Nodemon - Development server with auto-restart
- ESLint - Code linting
- Playwright - End-to-end testing
- Git - Version control
hotel-booking/
βββ hotel-booking-frontend/ # React frontend application
β βββ src/
β β βββ components/ # Reusable UI components
β β β βββ ui/ # Shadcn UI components
β β β βββ AdvancedSearch.tsx # Advanced search component
β β β βββ Hero.tsx # Landing page hero section
β β β βββ Header.tsx # Navigation header
β β β βββ ...
β β βββ pages/ # Page components
β β β βββ Home.tsx # Landing page
β β β βββ Search.tsx # Hotel search page
β β β βββ Detail.tsx # Hotel details page
β β β βββ Booking.tsx # Booking page
β β β βββ MyHotels.tsx # Hotel management
β β β βββ MyBookings.tsx # Booking management
β β β βββ AnalyticsDashboard.tsx # Analytics
β β β βββ ...
β β βββ forms/ # Form components
β β βββ hooks/ # Custom React hooks
β β βββ contexts/ # React contexts
β β βββ layouts/ # Layout components
β β βββ api-client.ts # API client functions
β βββ package.json
β βββ vite.config.ts
βββ hotel-booking-backend/ # Node.js backend application
β βββ src/
β β βββ routes/ # API route handlers
β β β βββ auth.ts # Authentication routes
β β β βββ hotels.ts # Hotel management routes
β β β βββ bookings.ts # Booking routes
β β β βββ analytics.ts # Analytics routes
β β β βββ ...
β β βββ models/ # MongoDB models
β β βββ middleware/ # Express middleware
β β βββ index.ts # Server entry point
β β βββ swagger.ts # API documentation
β βββ package.json
βββ shared/ # Shared TypeScript types
β βββ types.ts
βββ e2e-tests/ # End-to-end tests
βββ data/ # Sample data and images- Node.js (v18 or higher)
- MongoDB (local or Atlas)
- Git
git clone https://github.com/your-username/hotel-booking.git
cd hotel-bookingcd hotel-booking-backend
npm installcd hotel-booking-frontend
npm installCreate environment files for both frontend and backend (see Environment Variables section).
cd hotel-booking-backend
npm run dev
# Server runs on http://localhost:7002cd hotel-booking-frontend
npm run dev
# Frontend runs on http://localhost:5174- Frontend: http://localhost:5174
- Backend API: http://localhost:7002
- API Documentation: http://localhost:7002/api-docs
Create a .env file in the hotel-booking-backend directory:
# Server Configuration
PORT=7002
NODE_ENV=development
# MongoDB Connection
MONGODB_CONNECTION_STRING=mongodb://localhost:27017/hotel-booking
# OR for MongoDB Atlas:
# MONGODB_CONNECTION_STRING=mongodb+srv://username:password@cluster.mongodb.net/hotel-booking
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-here
JWT_EXPIRES_IN=7d
# Cloudinary Configuration (for image uploads)
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
# Stripe Configuration (for payments)
STRIPE_SECRET_KEY=sk_test_your-stripe-secret-key
STRIPE_PUBLISHABLE_KEY=pk_test_your-stripe-publishable-key
# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:5174
# Optional: Email Configuration (not used in this project yet)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-passwordCreate a .env file in the hotel-booking-frontend directory:
# API Configuration
VITE_API_BASE_URL=http://localhost:7002
# Stripe Configuration
VITE_STRIPE_PUBLISHABLE_KEY=pk_test_your-stripe-publishable-key
# Optional: Analytics (not used in this project yet)
VITE_GOOGLE_ANALYTICS_ID=GA_MEASUREMENT_ID- Create account at MongoDB Atlas
- Create a new cluster
- Get connection string from "Connect" button
- Replace
<password>with your database password
- Create account at Cloudinary
- Go to Dashboard β API Keys
- Copy Cloud Name, API Key, and API Secret
- Create account at Stripe
- Go to Developers β API Keys
- Copy Publishable Key and Secret Key (use test keys for development)
Generate a secure random string:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"Register a new user account.
interface RegisterData {
email: string;
password: string;
firstName: string;
lastName: string;
phone?: string;
address?: Address;
}Authenticate user and get JWT token.
interface LoginData {
email: string;
password: string;
}Logout user and invalidate session.
Validate JWT token and return user data.
Get all hotels with pagination and filtering.
interface HotelSearchParams {
destination?: string;
checkIn?: string;
checkOut?: string;
adultCount?: string;
childCount?: string;
page?: string;
facilities?: string[];
types?: string[];
stars?: string[];
maxPrice?: string;
sortOption?: string;
}Get specific hotel details.
Create a new hotel (requires authentication).
interface HotelFormData {
name: string;
city: string;
country: string;
description: string;
type: string[];
adultCount: number;
childCount: number;
facilities: string[];
pricePerNight: number;
starRating: number;
imageFiles: File[];
}Update hotel details.
Delete hotel listing.
Create a new booking.
interface BookingData {
firstName: string;
lastName: string;
email: string;
adultCount: number;
childCount: number;
checkIn: Date;
checkOut: Date;
totalCost: number;
}Get user's booking history.
Get all bookings for a specific hotel.
Get comprehensive business insights data.
interface BusinessInsightsData {
totalRevenue: number;
totalBookings: number;
overview: OverviewData;
popularDestinations: DestinationData[];
dailyBookings: BookingData[];
hotelPerformance: HotelData[];
}Get predictive forecasting data.
Get system statistics (memory, CPU, uptime, bookings).
Basic health check with status and uptime.
Detailed system metrics including memory usage and performance data.
A comprehensive search component with multiple filters and real-time suggestions.
// Usage Example
<AdvancedSearch
onSearch={(searchData) => {
// Handle search with advanced filters
console.log(searchData);
}}
isExpanded={false}
/>Features:
- Destination autocomplete with API suggestions
- Date range selection
- Guest count management
- Advanced filters (price, rating, facilities)
- Quick search for popular destinations
Landing page hero section with gradient background and search integration.
// Usage Example
<Hero
onSearch={(searchData) => {
// Handle search from hero section
}}
/>Features:
- Full-width gradient background
- Integrated search component
- Feature highlights
- Responsive design
Comprehensive analytics dashboard with charts and metrics.
// Usage Example
<AnalyticsDashboard />Features:
- Revenue charts and trends
- Booking analytics
- Performance metrics
- Forecasting data
- Interactive charts with Recharts
Modal for viewing detailed booking information.
// Usage Example
<BookingLogModal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
hotelId="hotel-id"
hotelName="Hotel Name"
/>Features:
- Detailed booking information
- Status management
- Payment details
- Guest information
interface UserType {
_id: string;
email: string;
password: string;
firstName: string;
lastName: string;
role: "user" | "admin" | "hotel_owner";
phone?: string;
address?: Address;
preferences?: UserPreferences;
totalBookings?: number;
totalSpent?: number;
lastLogin?: Date;
isActive?: boolean;
emailVerified?: boolean;
createdAt?: Date;
updatedAt?: Date;
}interface HotelType {
_id: string;
userId: string;
name: string;
city: string;
country: string;
description: string;
type: string[];
adultCount: number;
childCount: number;
facilities: string[];
pricePerNight: number;
starRating: number;
imageUrls: string[];
location?: Location;
contact?: Contact;
policies?: Policies;
amenities?: Amenities;
totalBookings?: number;
totalRevenue?: number;
averageRating?: number;
reviewCount?: number;
occupancyRate?: number;
isActive?: boolean;
isFeatured?: boolean;
createdAt?: Date;
updatedAt?: Date;
}interface BookingType {
_id: string;
userId: string;
hotelId: string;
firstName: string;
lastName: string;
email: string;
phone?: string;
adultCount: number;
childCount: number;
checkIn: Date;
checkOut: Date;
totalCost: number;
status: "pending" | "confirmed" | "cancelled" | "completed" | "refunded";
paymentStatus: "pending" | "paid" | "failed" | "refunded";
paymentMethod?: string;
specialRequests?: string;
cancellationReason?: string;
refundAmount?: number;
createdAt?: Date;
updatedAt?: Date;
}The application uses JWT tokens for secure authentication:
// Token generation
const token = jwt.sign(
{ userId: user._id, email: user.email, role: user.role },
process.env.JWT_SECRET!,
{ expiresIn: process.env.JWT_EXPIRES_IN },
);
// Token verification middleware
const verifyToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.cookies.auth_token;
if (!token) {
return res.status(401).json({ message: "Access denied" });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).json({ message: "Invalid token" });
}
};Different user roles have different permissions:
- User: Can book hotels, view their bookings
- Hotel Owner: Can manage their hotels, view analytics
- Admin: Full access to all features
// Role verification middleware
const requireRole = (roles: string[]) => {
return (req: Request, res: Response, next: NextFunction) => {
if (!roles.includes(req.userRole)) {
return res.status(403).json({ message: "Insufficient permissions" });
}
next();
};
};The application integrates with Stripe for secure payment processing:
// Create payment intent
const paymentIntent = await stripe.paymentIntents.create({
amount: totalCost * 100, // Convert to cents
currency: "usd",
metadata: {
hotelId,
userId,
bookingId,
},
});
// Payment confirmation
const confirmPayment = await stripe.paymentIntents.confirm(paymentIntentId, {
payment_method: paymentMethodId,
});- User selects hotel and dates
- System calculates total cost
- Stripe payment intent is created
- User completes payment
- Booking is confirmed
- Confirmation email is sent
The search system supports multiple filtering options:
// Search query building
const buildSearchQuery = (searchParams: SearchParams) => {
const query: any = {};
if (searchParams.destination) {
query.$or = [
{ city: { $regex: searchParams.destination, $options: "i" } },
{ country: { $regex: searchParams.destination, $options: "i" } },
{ name: { $regex: searchParams.destination, $options: "i" } },
];
}
if (searchParams.maxPrice) {
query.pricePerNight = { $lte: parseInt(searchParams.maxPrice) };
}
if (searchParams.facilities?.length) {
query.facilities = { $all: searchParams.facilities };
}
if (searchParams.types?.length) {
query.type = { $in: searchParams.types };
}
return query;
};Reusable filter components for different criteria:
// Price Filter Component
const PriceFilter = ({ onPriceChange }: PriceFilterProps) => {
const [priceRange, setPriceRange] = useState([0, 1000]);
return (
<div className="space-y-2">
<label className="text-sm font-medium">Price Range</label>
<Slider
value={priceRange}
onChange={setPriceRange}
min={0}
max={1000}
step={10}
/>
<div className="flex justify-between text-xs text-gray-500">
<span>Β£{priceRange[0]}</span>
<span>Β£{priceRange[1]}</span>
</div>
</div>
);
};The analytics dashboard provides comprehensive insights:
// Analytics data structure
interface AnalyticsData {
overview: {
totalRevenue: number;
totalBookings: number;
averageRating: number;
occupancyRate: number;
};
trends: {
revenue: RevenueData[];
bookings: BookingData[];
ratings: RatingData[];
};
topPerformers: {
hotels: HotelAnalytics[];
destinations: DestinationAnalytics[];
};
forecasts: {
revenue: ForecastData[];
bookings: ForecastData[];
};
}Interactive charts using Recharts library:
// Revenue Chart Component
const RevenueChart = ({ data }: { data: RevenueData[] }) => {
return (
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Line
type="monotone"
dataKey="revenue"
stroke="#8884d8"
strokeWidth={2}
/>
</LineChart>
</ResponsiveContainer>
);
};The project includes comprehensive E2E tests using Playwright:
# Run E2E tests
cd e2e-tests
npm install
npm test// Example test: Hotel search functionality
test("should search hotels with filters", async ({ page }) => {
await page.goto("/search");
// Fill search form
await page.fill('[data-testid="destination-input"]', "London");
await page.selectOption('[data-testid="adult-count"]', "2");
await page.click('[data-testid="search-button"]');
// Verify results
await expect(page.locator('[data-testid="hotel-card"]')).toHaveCount(5);
});- Authentication flows
- Hotel search and filtering
- Booking process
- Hotel management
- Analytics dashboard
- API endpoints
- Prepare for deployment:
cd hotel-booking-backend
npm run build-
Environment variables setup:
- Set all required environment variables in Coolify
- Ensure MongoDB connection string is production-ready
- Configure CORS for production domain
-
Deploy via Coolify:
- Connect your GitHub repository to Coolify
- Redeploy the backend service when you push changes
- Build the application:
cd hotel-booking-frontend
npm run build- Deploy to Netlify:
# Connect your GitHub repository
# Netlify will auto-deploy on push to main branch- Environment variables:
- Set
VITE_API_BASE_URLto your production backend URL - Configure Stripe keys for production
- Set
- Environment variables configured
- Database connection secured
- CORS settings updated
- SSL certificates installed
- Error monitoring setup
- Performance monitoring enabled
- Backup strategy implemented
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature- Make your changes and commit:
git commit -m 'Add amazing feature'- Push to your branch:
git push origin feature/amazing-feature- Open a Pull Request
- Follow TypeScript best practices
- Write comprehensive tests
- Update documentation
- Follow the existing code style
- Ensure all tests pass
This project is licensed under the MIT License - see the LICENSE file for details.
- Full-Stack Development: Complete MERN stack application
- TypeScript: Type-safe development practices
- Modern React: Hooks, Context API, React Query
- Database Design: MongoDB schema design and relationships
- Authentication: JWT-based authentication system
- Payment Integration: Stripe payment processing
- File Upload: Cloudinary image management
- API Design: RESTful API with Swagger documentation
- State Management: Server and client state management
- Testing: End-to-end testing with Playwright
- Deployment: Production deployment strategies
- Component Architecture: Reusable, modular components
- Form Handling: Complex forms with validation
- Search & Filtering: Advanced search with multiple criteria
- Analytics: Real-time data visualization
- Security: Authentication, authorization, and data protection
- Performance: Optimization techniques and best practices
- User Experience: Responsive design and accessibility
- React Documentation
- TypeScript Handbook
- MongoDB Documentation
- Express.js Guide
- Tailwind CSS Documentation
- Vite - Fast build tool
- Shadcn UI - Component library
- React Query - Data fetching
- Stripe - Payment processing
- Cloudinary - Image management
This is an open-source project - feel free to use, enhance, and extend this project further!
If you have any questions or want to share your work, reach out via GitHub or my portfolio at https://www.arnobmahmud.com/.
Enjoy building and learning! π
Thank you! π

















