🤖 AI ChatBot with LangChain & Google Gemini API A production-ready, full-stack AI chatbot application built with modern technologies. Features secure authentication, encrypted chat history, rate limiting, and a beautiful responsive UI.
✨ Features
🔒 Security & Authentication
JWT & API Key based authentication Password encryption with bcrypt End-to-end encrypted chat messages Input sanitization & validation Rate limiting per user/IP CORS protection
💬 Chat Features
Real-time conversation with Google Gemini AI Persistent chat history per session Markdown support in responses Copy messages to clipboard Conversation feedback (like/dislike) Multiple chat sessions Context-aware responses
🎨 UI/UX
Modern, responsive design with Tailwind CSS ShadCN UI components Dark/light mode ready Loading states & animations Mobile-friendly interface Toast notifications
🛠️ Developer Experience
Full TypeScript support Shared types between frontend/backend Environment-based configuration Comprehensive error handling API documentation Docker support
📋 Prerequisites
Node.js 18+ MongoDB 6.0+ Google Gemini API Key npm or yarn package manager
🚀 Quick Start
-
Clone the Repository bash git clone https://github.com/codingwalebhaiya/Qna-Chatbot cd Qna-Chatbot
-
Backend Setup
cd backend
npm install
Create .env file: env PORT=5000 MONGODB_URI=mongodb://localhost:27017/chatbot_db JWT_SECRET=your_super_secure_jwt_secret GOOGLE_GEMINI_API_KEY=your_gemini_api_key FRONTEND_URL=http://localhost:5173
- Frontend Setup
cd frontend npm install Create .env file: env VITE_API_URL=http://localhost:5000/api VITE_APP_NAME=AI ChatBot
- Start MongoDB
docker run -d -p 27017:27017 --name mongodb-chatbot mongo:latest
mongod
- Run Development Servers
cd backend npm run dev
cd frontend npm run dev
- Open Application Navigate to http://localhost:5173
📁 Project Structure text Qna-Chatbot/ ├── backend/ # Node.js + Express + TypeScript │ ├── src/ │ │ ├── models/ # MongoDB schemas │ │ ├── routes/ # API routes │ │ ├── services/ # Business logic │ │ ├── middleware/ # Auth & validation │ │ └── utils/ # Helper functions │ ├── .env # Environment variables │ └── package.json │ ├── frontend/ # React + TypeScript + Vite │ ├── src/ │ │ ├── components/ # React components │ │ ├── lib/ # API client & utilities │ │ └── App.tsx # Main app component │ ├── .env # Frontend environment │ └── package.json │ └── README.md
🔧 API Endpoints
Authentication Method Endpoint Description POST /api/auth/register Register new user POST /api/auth/login Login user GET /api/auth/profile Get user profile POST /api/auth/regenerate-api-key Regenerate API key
Chat Method Endpoint Description POST /api/chat Send message to chatbot GET /api/chat/history/:sessionId Get chat history
Health Method Endpoint Description GET /health Health check endpoint
🔐 Security Features
-
Authentication JWT tokens with expiration API key support for programmatic access Secure password hashing with bcrypt Account lockout prevention
-
Data Protection Encrypted chat messages in database Input sanitization against XSS attacks SQL/NoSQL injection prevention Secure HTTP headers with Helmet
-
Rate Limiting 100 requests per 15 minutes per user Different limits for free/premium users Redis-based rate limiting (optional)
-
Validation Zod schema validation Request payload sanitization File upload validation Content type checking
🎨 UI Components Built with ShadCN UI: Button - Customizable buttons with variants Input - Form input fields with validation Card - Content containers Avatar - User profile images Toast - Notification system ScrollArea - Custom scrollbars Custom Components: ChatInterface - Main chat interface MessageBubble - Individual chat messages AuthForm - Login/Registration forms UserProfile - Profile management ApiKeyManager - API key controls
📦 Dependencies Backend json { "express": "Web framework", "mongoose": "MongoDB ODM", "jsonwebtoken": "JWT authentication", "bcryptjs": "Password hashing", "langchain": "AI orchestration", "@langchain/google-genai": "Gemini integration", "zod": "Schema validation", "helmet": "Security headers", "cors": "Cross-origin support" } Frontend json { "react": "UI library", "axios": "HTTP client", "react-query": "Data fetching", "react-hook-form": "Form handling", "tailwindcss": "Styling", "shadcn/ui": "UI components", "lucide-react": "Icons", "date-fns": "Date formatting" }
🐳 Docker Deployment
- Docker Compose Setup
yaml
version: '3.8'
services:
mongodb:
image: mongo:latest
ports:
- "27017:27017" volumes:
- mongodb_data:/data/db
backend: build: ./backend ports: - "5000:5000" environment: - MONGODB_URI=mongodb://mongodb:27017/chatbot_db - GOOGLE_GEMINI_API_KEY=${GOOGLE_GEMINI_API_KEY} depends_on: - mongodb
frontend: build: ./frontend ports: - "5173:5173" environment: - VITE_API_URL=http://localhost:5000/api depends_on: - backend
volumes: mongodb_data:
- Build and Run
docker-compose up --build 🌐 Environment Variables Backend (.env) env
PORT=5000 MONGODB_URI=mongodb://localhost:27017/chatbot_db JWT_SECRET=your_jwt_secret_here GOOGLE_GEMINI_API_KEY=your_gemini_api_key
NODE_ENV=production FRONTEND_URL=http://localhost:5173 REDIS_URL=redis://localhost:6379 RATE_LIMIT_MAX=100 Frontend (.env) env VITE_API_URL=http://localhost:5000/api VITE_APP_NAME=AI ChatBot VITE_APP_VERSION=1.0.0
🔄 Development Workflow
- Code Structure TypeScript for type safety
Modular architecture for scalability
Shared types between frontend/backend
ESLint & Prettier for code quality
- Git Workflow
git checkout -b feature/new-chat-feature
git add . git commit -m "Add: New chat feature"
git push origin feature/new-chat-feature 3. Testing
cd backend npm test
cd frontend npm test
🚢 Deployment Option 1: Railway (Recommended)
railway up --service backend
railway up --service frontend Option 2: Render Backend: Web Service Frontend: Static Site Database: MongoDB Atlas
Option 3: Vercel + MongoDB Atlas Frontend: Vercel Backend: Vercel Serverless Functions Database: MongoDB Atlas
📊 Monitoring & Analytics Built-in Monitoring Request logging Error tracking Performance metrics Usage analytics Integration Options Sentry for error tracking
Google Analytics for user behavior LogRocket for session replay Prometheus for metrics
🔧 Troubleshooting Common Issues: MongoDB Connection Failed
sudo systemctl status mongod
docker start mongodb-chatbot CORS Errors
javascript // Ensure FRONTEND_URL matches your frontend origin FRONTEND_URL=http://localhost:5173 JWT Token Expired
bash
localStorage.clear() Rate Limit Exceeded
javascript // Check user's usage count // Premium users have higher limits
🤝 Contributing Fork the repository Create a feature branch Commit your changes Push to the branch Open a Pull Request Development Guidelines Follow TypeScript best practices Write meaningful commit messages Add tests for new features Update documentation Use descriptive variable names
📄 License This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments Google Gemini for AI capabilities LangChain for AI orchestration ShadCN UI for beautiful components Vite for fast development
📞 Support For support, email: [email protected] or open an issue in the GitHub repository.
🔗 Useful Links Google AI Studio - Get Gemini API Key LangChain Documentation - AI Orchestration MongoDB Atlas - Cloud Database Tailwind CSS - Styling Framework