# CLAUDE.md - AI Assistant Context ## Project Overview SiliconPin is a comprehensive web platform built with Next.js 15 that offers multiple services and tools for modern web development and hosting needs. The application provides: - **Topic Management System**: Rich content creation and management with user ownership - **Admin Dashboard**: Comprehensive analytics, user management, and service administration - **Web Services**: Cloud hosting, VPN, Kubernetes deployment, and developer hiring - **PWA Capabilities**: Full Progressive Web App with offline functionality - **Speech Tools**: Text-to-speech and voice recognition utilities - **Payment System**: Balance management and billing integration - **Authentication**: JWT-based auth with Redis sessions and OAuth integration ## Technology Stack ### Core Framework - **Next.js 15** - React framework with App Router - **TypeScript** - Type safety and better developer experience - **React 19** - Latest React with concurrent features ### UI & Styling - **Tailwind CSS 4** - Utility-first CSS framework - **Custom UI Components** - Reusable React components with Tailwind styling - **next-themes** - Dark/light theme support - **Lucide React** - Beautiful, customizable icons - **BlockNote Editor** - Rich text editor with @blocknote/mantine (v0.25.2) ### Authentication & Sessions - **JWT** - JSON Web Tokens for authentication - **bcryptjs** - Password hashing - **Redis** - Session storage (high performance) - **express-session** - Session management - **connect-redis** - Redis session store ### Database & Validation - **MongoDB** - Document database with Mongoose ODM - **Mongoose** - MongoDB object modeling - **Zod** - Schema validation and type inference - **Topic System** - User-owned content with rich text editing and BlockNote editor ### State Management - **TanStack Query v5** - Server state management - **React Context** - Client state management - **React Hook Form** - Form handling and validation ### Development Tools - **ESLint** - Code linting with Next.js config - **Prettier** - Code formatting with Tailwind plugin - **Husky** - Git hooks for code quality - **lint-staged** - Run linters on staged files ## Project Structure ``` siliconpin/ ├── app/ # Next.js App Router │ ├── api/ # Comprehensive API routes (auth, admin, topics, services, payments) │ ├── admin/ # Admin dashboard with analytics and management │ ├── auth/ # Authentication pages │ ├── topics/ # Topic management system (main content) │ ├── tools/ # Speech tools and utilities │ ├── services/ # Web services (hosting, VPN, K8s) │ ├── dashboard/ # User dashboard │ ├── globals.css # Global styles and Tailwind │ ├── layout.tsx # Root layout with providers │ └── page.tsx # Home page ├── components/ # React components │ ├── admin/ # Admin-specific components │ ├── auth/ # Authentication forms and UI │ ├── topics/ # Topic/content components │ ├── tools/ # Tool-specific components │ ├── BlockNoteEditor/ # Rich text editor component │ ├── ui/ # Reusable UI library │ ├── header.tsx # Header with navigation │ ├── footer.tsx # Footer component │ └── theme-*.tsx # Theme components ├── contexts/ # React contexts │ ├── AuthContext.tsx # Authentication state │ └── QueryProvider.tsx # TanStack Query provider ├── lib/ # Utility libraries │ ├── auth-middleware.ts # API authentication middleware │ ├── jwt.ts # JWT utilities │ ├── mongodb.ts # Database connection │ ├── redis.ts # Redis connection │ ├── session.ts # Session configuration │ └── utils.ts # General utilities ├── models/ # Database models │ ├── user.ts # User model with auth methods │ ├── topic.ts # Topic model with user ownership │ ├── billing.ts # Billing and payment models │ └── transaction.ts # Transaction tracking └── hooks/ # Custom React hooks ``` ## Key Features ### Authentication System - JWT-based authentication with refresh tokens - Secure HTTP-only cookies - Redis session storage for high performance - Protected routes and API middleware - User registration, login, logout, token refresh - User ownership model for content (blogs, etc.) ### API Routes - `POST /api/auth/register` - Create new user account - `POST /api/auth/login` - Sign in user - `POST /api/auth/logout` - Sign out user - `POST /api/auth/refresh` - Refresh access token - `GET /api/auth/me` - Get current user info (protected) ### Security Features - Secure HTTP-only cookies - Password hashing with bcrypt - CSRF protection headers - Input validation with Zod - Protected API middleware - Session management with Redis ### Core Application Features - **Topic Management** - User-owned content creation with rich text editing - **Admin Dashboard** - Comprehensive analytics, user management, and service administration - **Web Services** - Cloud hosting, VPN services, Kubernetes deployment, developer hiring - **Payment System** - Balance management, billing integration, and transaction tracking - **Speech Tools** - Text-to-speech and voice recognition utilities - **PWA Support** - Full Progressive Web App with offline capabilities and installability ## Development Commands ```bash # Development yarn dev # Start development server with hot reload yarn build # Build for production yarn start # Start production server # Code quality yarn lint # Run ESLint with auto-fix yarn typecheck # Run TypeScript compiler (no output) yarn prepare # Set up Husky pre-commit hooks ``` ## Environment Variables Required environment variables (create `.env.local`): ```env # Database MONGODB_URI=mongodb://localhost:27017/siliconpin # Redis Session Store REDIS_URL=redis://localhost:6379 # Authentication Secrets SESSION_SECRET=your-session-secret-must-be-at-least-32-characters-long JWT_SECRET=your-jwt-secret-change-in-production JWT_REFRESH_SECRET=your-jwt-refresh-secret-change-in-production # MinIO Storage (for topic images and file uploads) MINIO_ENDPOINT=your-minio-endpoint MINIO_PORT=9000 MINIO_ACCESS_KEY=your-access-key MINIO_SECRET_KEY=your-secret-key MINIO_BUCKET=your-bucket-name # Optional NODE_ENV=development PORT=3006 ``` ## Common Development Tasks ### Adding New API Routes 1. Create new route file in `app/api/` 2. Use the auth middleware for protected routes: ```typescript import { authMiddleware } from '@/lib/auth-middleware' export async function GET(request: Request) { const user = await authMiddleware(request) if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }) } // Your protected logic here } ``` ### Creating New Components 1. Add component in `components/` directory 2. Use custom UI components from components/ui/ when possible 3. Follow existing patterns for styling and props 4. Create index.ts barrel export for cleaner imports 5. Use dynamic imports for heavy components (e.g., BlockNote) ### Adding New Database Models 1. Create model in `models/` directory 2. Define Mongoose schema with proper types 3. Add Zod validation schema 4. Export both model and validation schema ### Form Handling Pattern ```typescript import { useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import { z } from 'zod' const schema = z.object({ // Define your schema }) export function MyForm() { const form = useForm({ resolver: zodResolver(schema), defaultValues: { // Set defaults }, }) // Handle form submission } ``` ## AI Assistant Instructions When working on this codebase: ### DO: - Use TypeScript for all new code - Follow existing component patterns - Use custom UI components from components/ui/ when building UI - Implement proper error handling - Add Zod validation for API inputs - Follow the established folder structure - Use the existing authentication patterns - Implement responsive design with Tailwind - Add proper loading and error states ### DON'T: - Mix different authentication patterns - Skip TypeScript types - Create components without proper props interface - Forget to handle loading/error states - Skip validation on API routes - Use different state management patterns - Add dependencies without checking existing ones ### Code Style - Use functional components with hooks - Prefer composition over inheritance - Use descriptive variable and function names - Add JSDoc comments for complex functions - Follow Prettier formatting rules - Use consistent import ordering ### Key Pages - `/auth` - Authentication and user management - `/dashboard` - User analytics and account overview - `/topics` - Public topic listing and content browsing - `/topics/new` - Create new topic (protected) - `/topics/[slug]` - View individual topic content - `/admin` - Admin dashboard with comprehensive management - `/services` - Web services (hosting, VPN, Kubernetes) - `/tools` - Speech tools and utilities ## 🔥 **CRITICAL: PWA Build vs Development Guidelines** ### **When You Need `yarn build` (Production Build Required):** - ✅ **Service Worker Changes** - New caching strategies, SW updates - ✅ **Workbox Configuration** - Changes to `next.config.js` PWA settings - ✅ **Production PWA Testing** - Final validation before deployment - ✅ **Performance Optimization** - Testing minified/optimized PWA bundle ### **When `yarn dev` is Sufficient (No Build Needed):** - ✅ **Manifest Changes** - Icons, name, description, screenshots, theme colors - ✅ **PWA Validation** - Chrome DevTools Application tab checks - ✅ **Install Button Testing** - Browser install prompts - ✅ **Icon Updates** - New icon files or sizes - ✅ **Most PWA Features** - Installability, offline detection, etc. ### **Quick PWA Development Workflow:** ```bash # 1. Start development (most PWA features work) yarn dev # 2. Make manifest/icon changes # 3. Refresh browser - changes appear immediately # 4. Validate in Chrome DevTools → Application → Manifest # 5. Only build when deploying or testing service worker yarn build && yarn start ``` **🚨 KEY INSIGHT**: PWA manifest changes hot-reload in development mode, making `yarn build` unnecessary for most PWA validation and testing! --- ## Troubleshooting ### Common Issues 1. **BlockNote Editor SideMenu Error** - **Solution**: Ensure using `@blocknote/mantine` v0.25.2 (not newer versions) - Import from `@blocknote/mantine` not `@blocknote/react` for BlockNoteView - Create index.ts barrel export in BlockNoteEditor folder - Clear cache: `rm -rf .next node_modules/.cache` - Clean install: `rm -rf node_modules yarn.lock && yarn install` 2. **MongoDB Connection Issues** - Ensure MongoDB is running locally or connection string is correct - Check network connectivity for cloud databases 3. **Redis Connection Issues** - Verify Redis server is running locally - Check REDIS_URL format: `redis://localhost:6379` 4. **Authentication Not Working** - Check JWT secrets are set in environment variables - Verify cookies are being set correctly - Check browser developer tools for errors 5. **Build Errors** - Run `yarn typecheck` to identify TypeScript errors - Check for unused imports or variables - Verify all environment variables are set 6. **Development Server Issues** - Clear Next.js cache: `rm -rf .next` - Reinstall dependencies: `rm -rf node_modules && yarn install` ## Deployment Notes - This application is optimized for Vercel deployment - Environment variables must be set in production - Ensure MongoDB and Redis instances are accessible from production - Use secure secrets for JWT and session keys - Enable HTTPS in production for secure cookies ## Contributing When extending this application: 1. Maintain the established patterns 2. Add proper TypeScript types 3. Include validation schemas 4. Update documentation as needed 5. Test authentication flows 6. Follow security best practices --- ## Application Status ### ✅ **PRODUCTION READY - COMPREHENSIVE PLATFORM** SiliconPin has evolved into a complete web platform with the following implemented features: #### **🔐 Authentication & User Management** - JWT-based authentication with refresh tokens - OAuth integration (Google, GitHub) - Redis session management - Protected routes and API middleware - User profile management #### **📝 Topic Management System** - Rich text editing with BlockNote editor - User-owned content creation and management - Tag system with search and filtering - Image upload with MinIO integration - Draft/publish workflows - SEO optimization with metadata #### **🛠️ Admin Dashboard** - Comprehensive analytics and reporting - User management and moderation - Billing and transaction tracking - Service administration - System settings and configuration - PDF report generation #### **🌐 Web Services** - Cloud hosting deployment and management - VPN service configuration - Kubernetes orchestration - Developer hiring marketplace - Service monitoring and health checks #### **🎤 Speech Tools** - Text-to-speech synthesis with multiple voices - Voice recognition and transcription - Web Speech API integration - Audio processing utilities #### **💰 Payment & Billing System** - Balance management and top-up - Transaction history and tracking - Service billing and invoicing - Payment gateway integration - Refund processing #### **📱 PWA Implementation** - Full Progressive Web App capabilities - Offline functionality with service worker - App installation and native feel - Responsive design across devices - Push notification support ### **🚀 Technical Architecture** #### **Backend Infrastructure** - **50+ API Endpoints**: Comprehensive REST API coverage - **8 Database Models**: User, Topic, Billing, Transaction, etc. - **MongoDB Integration**: Full CRUD operations with Mongoose - **Redis Caching**: High-performance session and data caching - **MinIO Storage**: File and image management #### **Frontend Excellence** - **150+ Component Library**: Reusable React components - **TypeScript**: 100% type safety with strict mode - **Tailwind CSS**: Modern, responsive design system - **Next.js 15**: Latest framework with App Router - **PWA Ready**: Installable with offline capabilities #### **Development Quality** - **Code Quality**: ESLint, Prettier, and Husky pre-commit hooks - **Security**: Input validation, CSRF protection, secure cookies - **Performance**: Optimized bundle, lazy loading, caching strategies - **Scalability**: Microservice-ready architecture - **Documentation**: Comprehensive developer documentation **Status**: **PRODUCTION DEPLOYMENT READY** with full feature set and enterprise-grade architecture.