A comprehensive, modern fleet management and analytics dashboard built with Next.js 15, React 19, MongoDB, and TypeScript. This application provides real-time fleet monitoring, data visualization, comparison tools, and interactive maps for dispatch management.
- Overview
- Features
- Tech Stack
- Project Structure
- Getting Started
- Environment Variables
- How It Works
- API Documentation
- Architecture
- Development
- Build & Deployment
- Troubleshooting
NextJS Dispatch Components is a full-stack web application designed for fleet management operations. It enables users to:
- Monitor Fleet Performance - Real-time analytics and metrics visualization
- Compare Simulations - Side-by-side comparison of different fleet scenarios
- Interactive Maps - Visualize fleet locations with Leaflet maps
- User Management - Role-based access control (HQ Manager & Fleet Manager)
- Data Analytics - Comprehensive charts for revenue, orders, delivery times, and more
The application uses JWT-based authentication, MongoDB for data persistence, and provides a responsive, modern UI built with Tailwind CSS and Radix UI components.
- JWT-based Authentication - Secure token-based login system
- Role-Based Access Control - Two authority levels:
- HQM (Headquarters Manager) - Full access to all fleets
- FM (Fleet Manager) - Access limited to assigned fleets/locations
- Cookie-based Session Management - HTTP-only cookies for security
- Interactive Charts - Multiple chart types (Area, Bar, Line) powered by Recharts
- Real-time Data Visualization - Live updates from MongoDB
- Fleet Metrics Dashboard - Comprehensive KPIs and performance indicators
- Chart Categories:
- Revenue Growth
- Order Volume
- Average Delivery Time
- Customer Satisfaction
- Fleet Utilization
- Driver Retention
- Side-by-Side Fleet Comparison - Compare two fleets simultaneously
- Multi-Chart Comparison - View all metrics across both fleets
- Search & Filter - Quick search across chart categories
- Interactive Leaflet Maps - Real-time fleet location visualization
- Map Navigation - Smooth fly-to animations
- Location Tracking - GPS coordinates for each fleet
- Modern Design - Clean, responsive UI with Tailwind CSS
- Component Library - Radix UI primitives for accessible components
- Dark Mode Support - Theme-aware components
- Mobile Responsive - Works seamlessly on all devices
- Next.js 15.3.2 - React framework with App Router
- React 19.0.0 - UI library
- TypeScript 5.0 - Type-safe development
- Tailwind CSS 4.0 - Utility-first CSS framework
- Radix UI - Accessible component primitives
- Recharts - Chart library
- React Leaflet - Map integration
- Lucide React - Icon library
- Next.js API Routes - Serverless API endpoints
- MongoDB - NoSQL database with Mongoose ODM
- JWT (jsonwebtoken) - Authentication tokens
- Node.js - Runtime environment
- pnpm - Fast, disk-efficient package manager
- ESLint - Code linting
- Turbopack - Next-generation bundler
- TypeScript - Static type checking
NextJS-DispatchComponents/
βββ app/ # Next.js App Router
β βββ api/ # API routes
β β βββ auth/ # Authentication endpoints
β β β βββ login/ # POST /api/auth/login
β β β βββ logout/ # POST /api/auth/logout
β β β βββ me/ # GET /api/auth/me
β β β βββ user/[id]/ # GET /api/auth/user/:id
β β βββ charts/ # Chart data endpoints
β β βββ fleets/ # GET /api/charts/fleets
β β βββ fleet/[name]/ # GET /api/charts/fleet/:name
β β βββ compare/ # POST /api/charts/compare
β βββ map/ # Map page
β βββ layout.tsx # Root layout
β βββ page.tsx # Home page
β βββ globals.css # Global styles
β
βββ components/ # React components
β βββ charts/ # Chart components
β β βββ AreaChartCard.tsx
β β βββ BarChartCard.tsx
β β βββ LineChartCard.tsx
β βββ map/ # Map components
β β βββ MapComponent.tsx
β β βββ LegendDropdown.tsx
β β βββ TimelineScrubber.tsx
β βββ ui/ # UI components
β β βββ DashboardCharts.tsx
β β βββ CompareSimulations.tsx
β β βββ ControlPanel.tsx
β β βββ Header.tsx
β β βββ Sidebar.tsx
β β βββ [shadcn components]
β βββ DashboardClient.tsx # Main dashboard client
β βββ mvpblocks/ # MVP-specific components
β
βββ lib/ # Utility libraries
β βββ auth.ts # Authentication helpers
β βββ mongo.ts # MongoDB connection
β βββ api-utils.ts # API utilities
β βββ utils.ts # General utilities
β
βββ models/ # Mongoose models
β βββ Fleet.ts # Fleet schema
β βββ User.ts # User schema
β
βββ hooks/ # Custom React hooks
β βββ useDebounce.ts # Debounce hook
β βββ use-mobile.ts # Mobile detection hook
β
βββ public/ # Static assets
β βββ Dispatchlogo.png # Logo file
β
βββ package.json # Dependencies & scripts
βββ pnpm-lock.yaml # pnpm lock file
βββ tsconfig.json # TypeScript configuration
βββ next.config.ts # Next.js configuration
βββ README.md # This file
Before you begin, ensure you have the following installed:
- Node.js >= 18.0.0
- pnpm >= 8.0.0 (Install:
npm install -g pnpm) - MongoDB connection string (or MongoDB Atlas account)
-
Clone the repository
git clone <repository-url> cd NextJS-DispatchComponents
-
Install dependencies using pnpm
pnpm install
-
Set up environment variables
Create a
.env.localfile in the root directory:JWT_SECRET=your-super-secret-jwt-key-here-minimum-32-characters MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database-name
Note: The MongoDB URI is currently hardcoded in
lib/mongo.ts. For production, move it to environment variables. -
Run the development server
pnpm dev
The application will start on http://localhost:2107
-
Build for production
pnpm build
-
Start production server
pnpm start
Create a .env.local file in the root directory with the following variables:
| Variable | Description | Required | Example |
|---|---|---|---|
JWT_SECRET |
Secret key for JWT token signing | Yes | your-secret-key-min-32-chars |
MONGODB_URI |
MongoDB connection string | Yes | mongodb+srv://user:pass@cluster.mongodb.net/db |
NODE_ENV |
Environment mode | No | development or production |
NEXT_PUBLIC_BASE_PATH |
Base path for deployment | No | /repo-name |
NEXT_STATIC_EXPORT |
Enable static export | No | true or false |
Security Note: Never commit .env.local to version control. Add it to .gitignore.
-
User Login
- User submits email and password via
/api/auth/login - Server validates credentials against MongoDB
- JWT token is generated with user ID and authority
- Token is stored in HTTP-only cookie
- User is redirected to dashboard
- User submits email and password via
-
Session Validation
- Each protected route calls
getAuthUser()to verify token - Token is extracted from cookie and verified with JWT
- User data is fetched from MongoDB using user ID
- Access is granted/denied based on authority
- Each protected route calls
-
Authorization
- HQM (Headquarters Manager): Can access all fleets
- FM (Fleet Manager): Can only access fleets matching their
locationorfleetfield
-
Fleet Data Retrieval
Client β API Route β MongoDB Query β Data Filtering β JSON Response β Chart Components -
Chart Rendering
- Fleet data is fetched via
/api/charts/fleet/:name - Chart components transform data into Recharts format
- Multiple chart types are rendered based on category
- Search functionality filters visible charts
- Fleet data is fetched via
-
Comparison Mode
- Two fleets are selected via dropdowns
- Data for both fleets is fetched in parallel
- Charts are rendered side-by-side in a grid layout
- Summary comparison is displayed at the bottom
- Leaflet Maps render fleet locations
- Map center is set based on fleet
locationcoordinates MapFlyTocomponent animates map transitions- Supports custom tile layers and attribution
Login endpoint for user authentication.
Request Body:
{
"email": "user@example.com",
"password": "password123"
}Response (Success):
{
"success": true,
"user": {
"_id": "user-id",
"username": "username",
"email": "user@example.com",
"authority": "HQM",
"location": "Pune",
"fleet": "Fleet Name"
}
}Status Codes:
200- Success400- Invalid request body401- Invalid credentials500- Server error
Logout endpoint that clears authentication cookie.
Response:
{
"success": true,
"message": "Logged out successfully"
}Get current authenticated user information.
Response:
{
"loggedIn": true,
"user": {
"_id": "user-id",
"username": "username",
"email": "user@example.com",
"authority": "HQM",
"location": "Pune",
"fleet": "Fleet Name"
}
}Status Codes:
200- Success (loggedIn: false if not authenticated)
Get user information by ID.
Response:
{
"username": "username",
"email": "user@example.com",
"authority": "HQM",
"location": "Pune",
"fleet": "Fleet Name"
}Get list of all accessible fleets based on user authority.
Authorization Required: Yes
Response:
[
{
"name": "Zomato Fleet Pune",
"location": {
"lat": 18.5204,
"lng": 73.8567
},
"charts": [...]
}
]Authority Filtering:
- HQM: Returns all fleets
- FM: Returns fleets matching user's
locationorfleet
Get specific fleet data including charts.
Parameters:
name(URL parameter): Fleet name (URL encoded)
Response:
{
"name": "Zomato Fleet Pune",
"location": {
"lat": 18.5204,
"lng": 73.8567
},
"charts": [
{
"category": "Revenue Growth",
"data": [100, 120, 140, 160, 180, 200, 220],
"summary": "Revenue increased by 120%"
}
],
"fleetId": "fleet-mongodb-id"
}Compare multiple chart categories across fleets.
Request Body:
{
"fleet": "Zomato Fleet Pune",
"categories": ["Revenue Growth", "Order Volume", "Fleet Utilization"]
}Response:
[
{
"category": "Revenue Growth",
"data": [100, 120, 140],
"summary": "Revenue increased by 120%"
}
]- Server Components - Initial page load and data fetching
- Client Components - Interactive UI with React hooks
- Dynamic Imports - Code splitting for heavy components
- Custom Hooks - Reusable logic (debounce, mobile detection)
- API Routes - Serverless functions in
app/api - Middleware Pattern - Authentication checks via
getAuthUser() - Database Connection - Singleton pattern with caching (MongoDB)
- Error Handling - Consistent error responses across endpoints
{
username: string; // Unique username
email: string; // Unique email
password: string; // Plain text (consider hashing)
authority: "FM" | "HQM"; // User role
location?: string; // Optional location
fleet?: string; // Optional fleet assignment
}{
name: string; // Unique fleet name
location: {
lat: number; // Latitude
lng: number; // Longitude
};
charts: [{
category: string; // Chart category name
data: number[]; // Array of data points
summary: string; // Summary text
}];
}# Start development server with Turbopack
pnpm dev
# Build for production
pnpm build
# Start production server
pnpm start
# Run linter
pnpm lint
# Static export (for GitHub Pages)
pnpm build:staticThe development server runs on port 2107 by default with Turbopack enabled for faster builds.
pnpm dev
# Server: http://localhost:2107- Functions: Keep under 20 lines when possible
- Variables: Use descriptive names
- Code: Optimized with low time complexity
- Reusability: Avoid duplicate code
- Testing: Follow TDD principles (write tests before implementation)
- Components: Reusable UI components in
components/ - API Routes: Server endpoints in
app/api/ - Utilities: Shared functions in
lib/ - Models: Database schemas in
models/ - Hooks: Custom React hooks in
hooks/
# Install dependencies
pnpm install
# Build the application
pnpm build
# Start production server
pnpm start# Set environment variable
export NEXT_STATIC_EXPORT=true
# Build and export
pnpm build:static
# Output will be in ./out directory- Connect your GitHub repository to Vercel
- Set environment variables in Vercel dashboard
- Deploy automatically on push
FROM node:18-alpine
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install
COPY . .
RUN pnpm build
EXPOSE 3000
CMD ["pnpm", "start"]- Build the application:
pnpm build - Start the server:
pnpm start - Configure reverse proxy (nginx/Apache)
- Set up PM2 or similar process manager
Problem: Cannot connect to MongoDB
Solutions:
- Verify MongoDB URI is correct
- Check network firewall settings
- Ensure MongoDB Atlas IP whitelist includes your IP
- Verify credentials are correct
Problem: Authentication fails or tokens expire
Solutions:
- Check
JWT_SECRETis set in environment variables - Ensure secret is at least 32 characters
- Verify cookie settings match your domain
Problem: Port 2107 is already in use
Solutions:
- Change port in
package.json:"dev": "next dev -p 3000" - Kill process using port:
lsof -ti:2107 | xargs kill
Problem: TypeScript or build errors
Solutions:
- Run
pnpm installto ensure dependencies are up to date - Check TypeScript version compatibility
- Clear
.nextfolder:rm -rf .next - Run
pnpm lintto identify issues
Problem: Leaflet map doesn't render
Solutions:
- Ensure
react-leafletandleafletare installed - Check CSS import:
import "leaflet/dist/leaflet.css" - Verify Leaflet styles are loaded globally
- Password Storage: Currently passwords are stored in plain text. Implement bcrypt hashing for production.
- JWT Secret: Use a strong, random secret (minimum 32 characters).
- HTTP-Only Cookies: Already implemented for token storage.
- Input Sanitization: Use
sanitizeInpututility for user inputs. - CORS: Configure CORS if using separate frontend/backend.
- Code Splitting: Dynamic imports for heavy components
- Database Indexing: Add indexes on frequently queried fields
- Caching: MongoDB connection caching implemented
- Debouncing: Search queries are debounced to reduce API calls
- Lazy Loading: Charts and maps load on demand
- Add password hashing (bcrypt)
- Implement refresh tokens
- Add data export functionality
- Real-time updates via WebSockets
- Advanced filtering and sorting
- Multi-language support
- Unit and integration tests
- CI/CD pipeline setup
This project is private and proprietary. All rights reserved.
This is a private project. For contributions, please contact the project maintainers.
For issues, questions, or support, please open an issue in the repository or contact the development team.
Made with β€οΈ using Next.js, React, and TypeScript