License: MIT Node.js React TypeScript
FuelMate is a comprehensive on-demand fuel delivery management system built with the MERN stack. It provides a seamless platform connecting customers, fuel stations, and delivery personnel for efficient fuel delivery services.
- Features
- Tech Stack
- Project Structure
- Getting Started
- Installation
- Environment Variables
- Running the Application
- API Documentation
- Challenges and solutions
- Future enhancements
- Contributing
- License
- π User authentication and authorization
- π Real-time location-based fuel ordering
- π³ Multiple payment options
- π± Order tracking and history
- β Rating and review system
- π Push notifications for order updates
- π Dashboard with analytics
- π¦ Order management system
- π₯ Delivery personnel management
- π Revenue tracking
- π Service area management
- πΊοΈ Route optimization
- π Order assignment and tracking
- π° Earnings dashboard
- π Performance metrics
- π¨βπΌ User management
- πͺ Station management
- π System-wide analytics
- π§ Configuration management
- React 18.3 - UI library
- TypeScript - Type safety
- Vite - Build tool and dev server
- Tailwind CSS - Utility-first CSS framework
- shadcn/ui - Component library
- React Router - Client-side routing
- TanStack Query - Data fetching and caching
- Recharts - Data visualization
- Mapbox GL - Interactive maps
- Node.js - Runtime environment
- Express.js - Web framework
- MongoDB - NoSQL database
- Mongoose - ODM for MongoDB
- Redis - In-memory store for OTP management and analytics caching
- ioredis - Redis client for Node.js
- JWT - Authentication
- bcrypt - Password hashing
- Winston - Professional logging with file rotation
- ESLint - Code linting
- Nodemon - Auto-restart server
- Git - Version control
- loglevel - Client-side logging
Fuel-Mate/
βββ π public/ # Static assets
β βββ favicon.ico # App favicon
β βββ robots.txt # SEO robots file
β
βββ π server/ # Backend application
β βββ π controllers/ # Request handlers
β βββ π middleware/ # Custom middleware
β βββ π models/ # Mongoose schemas
β βββ π routes/ # API routes
β βββ π lib/ # Utilities and helpers
β βββ index.js # Database connection
β βββ server.js # Express server setup
β
βββ π src/ # Frontend application
β βββ π components/ # React components
β β βββ π ui/ # shadcn/ui components
β β βββ ... # Custom components
β βββ π contexts/ # React contexts
β βββ π hooks/ # Custom React hooks
β βββ π lib/ # Utilities
β βββ π models/ # TypeScript types/interfaces
β βββ π pages/ # Page components
β βββ π routes/ # Route configurations
β βββ π services/ # API services
β βββ App.tsx # Root component
β βββ main.tsx # Entry point
β βββ index.css # Global styles
β
βββ π .env # Environment variables (not in git)
βββ π .gitignore # Git ignore rules
βββ π components.json # shadcn/ui config
βββ π eslint.config.js # ESLint configuration
βββ π index.html # HTML template
βββ π package.json # Dependencies and scripts
βββ π postcss.config.js # PostCSS configuration
βββ π tailwind.config.ts # Tailwind CSS config
βββ π tsconfig.json # TypeScript config
βββ π tsconfig.app.json # App TypeScript config
βββ π tsconfig.node.json # Node TypeScript config
βββ π vite.config.ts # Vite configuration
βββ π README.md # This file
Before you begin, ensure you have the following installed:
- Node.js (v18 or higher)
- npm or yarn
- MongoDB (local or Atlas)
- Redis (local via
redis-server, or Docker:docker run -p 6379:6379 redis) - Git
- Clone the repository
git clone https://github.com/Vishwas1345/Fuel-Mate.git
cd Fuel-Mate- Install dependencies
npm install- Set up environment variables
# Create .env file in the root directory
cp .env.example .env
# Edit .env with your configurationCreate a .env file in the root directory with the following variables:
# Server Configuration
PORT=5000
NODE_ENV=development
# Database
MONGODB_URI=mongodb://localhost:27017/fuelmate
# Or use MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/fuelmate
# Redis
REDIS_URL=redis://localhost:6379
# Or with authentication:
# REDIS_URL=redis://:yourpassword@localhost:6379
# JWT Secret
JWT_SECRET=your_super_secret_jwt_key_here_change_in_production
# Frontend URL (for CORS)
CLIENT_URL=http://localhost:5173
# Mapbox (for maps)
VITE_MAPBOX_TOKEN=your_mapbox_token_here
# Payment Gateway (if applicable)
PAYMENT_API_KEY=your_payment_api_key
# Logging Configuration
LOG_LEVEL=debug # Server: error, warn, info, http, debug
VITE_LOG_LEVEL=debug # Client: trace, debug, info, warn, errorFuelMate uses professional logging libraries for both client and server:
- Colored console output for easy debugging
- Daily rotating log files in
server/logs/ - Separate error logs for quick issue identification
- Automatic exception handling
- Colored browser console output
- Timestamp formatting
- Helper methods for API calls, components, and actions
- Dynamic log level changes
Server:
import logger from './utils/logger.js';
logger.info('User logged in', { userId: user.id });
logger.error('Database error', { error: err.message });Client:
import logger from '@/utils/logger';
logger.info('Component mounted');
logger.api('POST', '/api/orders', { orderId: '123' });- π Full Guide: See
LOGGER_USAGE.mdfor comprehensive documentation - π Quick Reference: See
LOGGER_SETUP.mdfor setup summary - π‘ Examples: Check
server/examples/andclient/examples/
Logs are saved to server/logs/:
application-YYYY-MM-DD.log- All logserror-YYYY-MM-DD.log- Errors onlyexceptions-YYYY-MM-DD.log- Uncaught exceptionsrejections-YYYY-MM-DD.log- Unhandled rejections
## β‘ Redis Integration
FuelMate uses Redis as a fast, expiry-aware layer alongside MongoDB. The client is set up in `server/lib/redis.js` using **ioredis** with exponential retry and graceful degradation β if Redis is unavailable, the app continues to function normally.
### OTP Storage
Email verification OTPs are stored entirely in Redis instead of the User document.
| Detail | Value |
|---|---|
| Key | `otp:<email>` |
| Fields | `hash` (bcrypt), `attempts` |
| TTL | **10 minutes** (auto-deleted by Redis) |
| Max attempts | 5 |
**Why Redis for OTPs?**
- OTPs are temporary β Redis TTL handles expiry automatically, no cleanup queries needed
- Failed attempts increment a counter in Redis, no MongoDB write required
- The `User` model stays clean β no `emailVerificationOtpHash`, `emailVerificationOtpExpires`, or `emailVerificationAttempts` fields
### Analytics Caching
The `GET /api/analytics` endpoint caches its aggregated result in Redis.
| Detail | Value |
|---|---|
| Key | `analytics:<userId>` |
| TTL | **5 minutes** |
| Invalidation | Immediately on order status β `delivered` |
**How it works:**
1. Request hits `/api/analytics`
2. Cache hit β returns JSON in ~0.2ms
3. Cache miss β aggregates all delivered orders from MongoDB, stores result in Redis, responds
4. When a station marks an order as `delivered`, both the customer's and station's cache keys are deleted so the next load reflects real data
### Local Setup
Start Redis before running the server:
```bash
# Option A β local Redis
redis-server
# Option B β Docker
docker run -p 6379:6379 redis
Set REDIS_URL in server/.env:
REDIS_URL=redis://localhost:6379Run Frontend (Vite Dev Server)
npm run devThe frontend will be available at http://localhost:5173
Run Backend (Node.js Server)
npm run server:devThe backend API will be available at http://localhost:5000
Run Both Concurrently
# In separate terminals:
# Terminal 1:
npm run dev
# Terminal 2:
npm run server:devBuild Frontend
npm run buildRun Backend
npm run serverPreview Production Build
npm run previewhttp://localhost:5000/api
POST /api/auth/register- Register new userPOST /api/auth/login- User loginGET /api/auth/me- Get current user
GET /api/orders- Get all ordersPOST /api/orders- Create new orderGET /api/orders/:id- Get order by IDPUT /api/orders/:id- Update orderDELETE /api/orders/:id- Delete order
GET /api/users- Get all usersGET /api/users/:id- Get user by IDPUT /api/users/:id- Update userDELETE /api/users/:id- Delete user
FuelMate sits between customers, stations, and field delivery, so several design tensions show up in the product and codebase:
| Challenge | Solution |
|---|---|
| Identity and trust on signup β email accounts need to be real before users order fuel or stations go live. | Email OTP for local registration (bounded attempts, resend + expiry), Google OAuth for verified-email sign-in, and JWT + httpOnly refresh so sessions stay usable without exposing long-lived tokens in JS. |
| One product, two roles (and one data model) β customers and stations share auth and listings but need different profiles, dashboards, and permissions. | A single User collection with role (customer / station) and role-specific fields; stations are users referenced by stationId on orders so analytics and listings stay consistent. |
| Analytics when history is thin or APIs partial β charts and βinsightsβ break if there are no delivered orders or missing profile fragments (e.g. pump location). | Server-side aggregates where possible, client fallbacks rebuilt from delivered orders, defensive UI (optional chaining / placeholders), and rules-based dashboard copy instead of hard-coded fake AI so messaging tracks real data. |
| OAuth hijacking the whole browser tab β a full redirect to Google pulls users out of sign-up context and feels heavy. | Popup-based Google sign-in (window.open to /api/auth/google), **postMessage** from /auth/callback back to the opener, then the main tab finishes login; refresh cookies still work because they are scoped to the API host, not the window. |
| Deliverability and local development β OTP and notifications must send in production but engineers often lack mail infra locally. | Central **mailService** using SendGrid when **SENDGRID_API_KEY** is set; clear logging / safe fallbacks when mail is disabled so verification flows remain testable without leaking secrets in responses. |
| Short-lived access tokens vs smooth UX β aggressive access JWT expiry improves security but breaks tabs mid-session. | **POST /api/auth/refresh-token** with httpOnly refresh cookies (and optional stored refresh fallback), plus a fetch layer that only retries with refresh on protected routesβnot on login/register/verify, so bad credentials are not mistaken for expired sessions. |
| Onboarding fatigue for returning users β new flows should not repeat after every login or OAuth return. | **isProfileComplete** on the user record plus a per-user βonboarding seenβ flag in localStorage so first-time signups see setup once, while returning users go straight to the customer or station dashboard. |
| Temporary OTP state polluting the User model β storing hash, expiry, and attempt count as MongoDB fields means manual cleanup and a write on every failed attempt. | OTP stored entirely in Redis (otp:<email> hash, 10-minute TTL). Redis TTL handles expiry automatically, failed attempts increment a counter in-place without a MongoDB write, and the key self-destructs on success β the User document never holds OTP state. |
| Analytics recalculated on every dashboard load β full MongoDB scan of delivered orders on every request is slow and wasteful for both the station and customer dashboards. | Redis cache (analytics:<userId>, 5-minute TTL). Cache hit returns in ~0.2ms. Cache is invalidated immediately when an order is marked delivered so dashboards always reflect real data without polling. |
Short-term and longer-term directions that would deepen FuelMate without changing the core MERN shape of the product:
- Payments and fulfilment β Integrate a real payment gateway (UPI / cards) with webhooks for settlement status, plus SMS or WhatsApp order updates so customers and drivers are notified outside the browser.
- Operations β Driver mobile app or PWA with GPS pings, dispatch rules (auto-assign, SLA alerts), and inventory / bowser checks so stations cannot oversell capacity in peak windows.
- Trust and scale β KYC-lite for stations, richer review moderation, admin console for disputes and pricing audits, and horizontal scaling (job queues for mail/analytics, read replicas, or caching hot station lists).
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Vishwas
- GitHub: @Vishwas1345
- shadcn/ui for the beautiful component library
- Tailwind CSS for the utility-first CSS framework
- Vite for the blazing fast build tool
- MongoDB for the database
Made with β€οΈ by Vishwas