{"id":32337600,"url":"https://github.com/mostafa-drz/nextjs-dify-firebase-starter","last_synced_at":"2026-04-30T12:33:13.932Z","repository":{"id":320175493,"uuid":"1081091166","full_name":"mostafa-drz/nextjs-dify-firebase-starter","owner":"mostafa-drz","description":"Full-stack Next.js 15 starter for AI apps. Includes Firebase Auth, Dify AI, credit management, and streaming chat.","archived":false,"fork":false,"pushed_at":"2025-10-22T10:08:12.000Z","size":603,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-30T12:33:09.455Z","etag":null,"topics":["dify","firebase","full-stack-ai","nextjs15","vercel"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mostafa-drz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-22T09:49:31.000Z","updated_at":"2025-12-31T08:12:23.000Z","dependencies_parsed_at":"2025-10-22T12:19:10.694Z","dependency_job_id":null,"html_url":"https://github.com/mostafa-drz/nextjs-dify-firebase-starter","commit_stats":null,"previous_names":["mostafa-drz/nextjs-dify-firebase-starter"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/mostafa-drz/nextjs-dify-firebase-starter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mostafa-drz%2Fnextjs-dify-firebase-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mostafa-drz%2Fnextjs-dify-firebase-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mostafa-drz%2Fnextjs-dify-firebase-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mostafa-drz%2Fnextjs-dify-firebase-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mostafa-drz","download_url":"https://codeload.github.com/mostafa-drz/nextjs-dify-firebase-starter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mostafa-drz%2Fnextjs-dify-firebase-starter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32465009,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T22:27:22.272Z","status":"online","status_checked_at":"2026-04-30T02:00:05.929Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dify","firebase","full-stack-ai","nextjs15","vercel"],"created_at":"2025-10-23T23:26:40.124Z","updated_at":"2026-04-30T12:33:13.909Z","avatar_url":"https://github.com/mostafa-drz.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Next.js Dify Firebase Starter\n\nA secure Next.js 15 boilerplate for integrating [Dify.ai](https://dify.ai) with Firebase authentication and credit-based usage tracking. This project provides a complete foundation for building AI-powered applications with proper user management and cost tracking.\n\n## 📑 Table of Contents\n\n- [🚀 Features](#-features)\n  - [Core Features](#core-features)\n  - [Security Features](#security-features)\n  - [User Experience](#user-experience)\n- [📋 Prerequisites](#-prerequisites)\n- [🛠️ Setup Instructions](#️-setup-instructions)\n  - [1. Installation](#1-installation)\n  - [2. Firebase Project Setup](#2-firebase-project-setup)\n  - [3. Environment Configuration](#3-environment-configuration)\n  - [4. Firestore Security Rules Setup](#4-firestore-security-rules-setup)\n  - [5. Dify.ai Setup](#5-difyai-setup)\n  - [6. Start Development Server](#6-start-development-server)\n- [🔨 Development Experience](#-development-experience)\n  - [Development Tools Setup](#development-tools-setup)\n  - [Available Scripts](#available-scripts)\n  - [IDE Setup (VSCode/Cursor)](#ide-setup-vscodecursor)\n  - [First-Time Setup for New Developers](#first-time-setup-for-new-developers)\n  - [Code Formatting Rules](#code-formatting-rules)\n  - [Quality Checks](#quality-checks)\n  - [Troubleshooting](#troubleshooting)\n- [🎯 Usage](#-usage)\n  - [Basic Integration](#basic-integration)\n  - [Streaming Chat (New!)](#streaming-chat-new)\n  - [Credit Management](#credit-management)\n  - [Server Actions](#server-actions)\n- [💬 Conversation Management](#-conversation-management)\n  - [Architecture Overview](#architecture-overview)\n  - [Data Flow](#data-flow)\n  - [Usage Examples](#usage-examples)\n  - [Performance Features](#performance-features)\n  - [Extending the System](#extending-the-system)\n  - [Debug Tools](#debug-tools)\n  - [Best Practices](#best-practices)\n- [🏗️ Project Structure](#️-project-structure)\n- [🔧 Configuration](#-configuration)\n  - [Credit System](#credit-system)\n  - [Dify Apps](#dify-apps)\n- [🧪 Testing](#-testing)\n  - [Testing Philosophy](#testing-philosophy)\n  - [Run Tests](#run-tests)\n  - [Test Coverage](#test-coverage)\n  - [Test Structure](#test-structure)\n  - [Test Credit System](#test-credit-system)\n  - [Test Dify Integration](#test-dify-integration)\n  - [Test Sentry Integration](#test-sentry-integration)\n  - [Enable Google Analytics](#enable-google-analytics)\n- [🌍 Adding More Languages](#-adding-more-languages)\n  - [Adding a New Language (e.g., Spanish)](#adding-a-new-language-eg-spanish)\n  - [Context Integration](#context-integration)\n- [🚀 Deployment](#-deployment)\n  - [Vercel (Recommended)](#vercel-recommended)\n  - [Other Platforms](#other-platforms)\n- [📊 Monitoring](#-monitoring)\n  - [Firebase Console](#firebase-console)\n  - [Sentry Error Tracking](#sentry-error-tracking)\n  - [Application Monitoring](#application-monitoring)\n  - [Google Analytics Integration](#google-analytics-integration)\n- [🔐 Authentication System](#-authentication-system)\n  - [How It Works](#how-it-works)\n  - [Security Features](#security-features-1)\n  - [Files](#files)\n- [🛡️ Security Considerations](#️-security-considerations)\n- [🤝 Contributing](#-contributing)\n- [📄 License](#-license)\n- [🆘 Support](#-support)\n- [🚀 Release Management](#-release-management)\n  - [How It Works](#how-it-works-1)\n  - [Setup](#setup)\n  - [Usage](#usage-1)\n  - [Configuration](#configuration)\n  - [First Release](#first-release)\n- [📚 Additional Documentation](#-additional-documentation)\n- [🚧 Roadmap](#-roadmap)\n  - [✅ Completed Features](#-completed-features)\n  - [🔄 Planned Features](#-planned-features)\n\n## 🚀 Features\n\n### Core Features\n\n- ✅ **Next.js 15** with App Router and Server Actions\n- ✅ **Firebase Authentication** with magic link (passwordless) login\n- ✅ **Firestore Database** with security rules and real-time updates\n- ✅ **Credit Management System** with token-based deduction (1 credit = 1000 tokens)\n- ✅ **Secure Dify.ai Integration** using server-side API calls only\n- ✅ **TypeScript** for type safety\n- ✅ **Tailwind CSS 4** with shadcn/ui components\n- ✅ **ESLint \u0026 Prettier** for code quality\n- ✅ **Google Analytics** with Firebase Analytics integration\n\n### Security Features\n\n- 🔒 **HTTP-only cookie authentication** - Secure Firebase ID token handling\n- 🔒 **API keys never exposed** to client-side code\n- 🔒 **Server-side validation** for all Dify API calls\n- 🔒 **Credit pre-flight checks** to prevent unauthorized usage\n- 🔒 **Atomic transactions** for credit deduction\n- 🔒 **Firebase security rules** protecting user data\n- 🔒 **Sentry error tracking** with privacy-first configuration\n\n### User Experience\n\n- 📱 **Responsive design** for all screen sizes\n- ⚡ **Real-time credit updates** via Firestore listeners\n- 💬 **Custom chat interface** with token usage tracking\n- 📊 **Credit history and usage analytics**\n- 🎨 **Modern UI** with loading states and error handling\n- 🔄 **Conversation management** with React Query caching\n- ⚡ **Optimistic updates** for instant UI feedback\n- 🌊 **Real-time streaming chat** with production-ready error handling and retry logic\n\n## 📋 Prerequisites\n\n- Node.js 18+ and npm/yarn\n- Firebase project with Firestore and Authentication enabled\n- Dify.ai account with API access\n\n## 🛠️ Setup Instructions\n\n### 1. Installation\n\n```bash\ngit clone https://github.com/mostafa-drz/nextjs-dify-firebase-starter.git\ncd nextjs-dify-firebase-starter\nnpm install\n```\n\n### 2. Firebase Project Setup\n\n1. **Create Firebase Project**\n   - Visit [Firebase Console](https://console.firebase.google.com/)\n   - Click \"Create a project\"\n   - Follow the setup wizard\n\n2. **Enable Authentication**\n   - Go to Authentication → Sign-in method\n   - Enable **Email/Password** provider\n   - (Optional) Enable **Google** provider for OAuth\n\n3. **Setup Firestore Database**\n   - Go to Firestore Database\n   - Click \"Create database\"\n   - Choose \"Production mode\"\n   - Select your preferred location\n\n4. **Generate Service Account Key**\n   - Go to Project Settings → Service accounts\n   - Click \"Generate new private key\"\n   - Download the JSON file (keep it secure)\n\n5. **Enable Analytics** (Optional)\n   - Go to Analytics → Dashboard\n   - Follow setup steps if not already enabled\n   - Copy the Measurement ID from Data Streams\n\n### 3. Environment Configuration\n\nCopy `.env.example` to `.env.local` and fill in your values:\n\n```bash\ncp .env.example .env.local\n```\n\nRequired environment variables:\n\n```env\n# Firebase Client Configuration\nNEXT_PUBLIC_FIREBASE_API_KEY=your_api_key\nNEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project.firebaseapp.com\nNEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id\nNEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_project.appspot.com\nNEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_sender_id\nNEXT_PUBLIC_FIREBASE_APP_ID=your_app_id\nNEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX\n\n# Firebase Admin (Server-side)\nFIREBASE_PROJECT_ID=your_project_id\nFIREBASE_CLIENT_EMAIL=your_service_account_email\nFIREBASE_PRIVATE_KEY=\"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n\"\n\n# Dify AI Configuration\nDIFY_API_KEY=your_dify_api_key\nDIFY_BASE_URL=https://api.dify.ai/v1\n\n# Application Configuration\nNEXT_PUBLIC_SUPPORT_EMAIL=support@yourdomain.com\n\n# Sentry Configuration (Optional)\nNEXT_PUBLIC_SENTRY_DSN=https://your_public_key@o0.ingest.sentry.io/0\nSENTRY_DSN=https://your_public_key@o0.ingest.sentry.io/0\nSENTRY_AUTH_TOKEN=your_sentry_auth_token_here\nSENTRY_ORG=your_sentry_org_slug\nSENTRY_PROJECT=your_sentry_project_slug\n\n# App Configuration\nSUPPORT_EMAIL=support@yourdomain.com\nNEXT_PUBLIC_SUPPORT_EMAIL=support@yourdomain.com\n```\n\n### 4. Firestore Security Rules Setup\n\nDeploy the security rules to protect your data:\n\n```bash\n# Install Firebase CLI globally\nnpm install -g firebase-tools\n\n# Login to Firebase\nfirebase login\n\n# Initialize Firestore in your project\nfirebase init firestore\n# - Select your existing Firebase project\n# - Keep default firestore.rules file\n# - Keep default firestore.indexes.json file\n\n# Deploy the security rules\nfirebase deploy --only firestore:rules\n```\n\n### 5. Dify.ai Setup\n\n1. **Get Dify API Key**\n   - Visit [Dify.ai](https://dify.ai) and create account\n   - Create a new app or use existing one\n   - Copy the API key from app settings\n\n2. **Configure App Settings**\n   - Ensure your Dify app supports the required endpoints\n   - Configure any necessary conversation settings\n   - Test the API key works with your app\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nOpen [http://localhost:3000](http://localhost:3000) to see the application.\n\n## 🔨 Development Experience\n\nThis project includes a comprehensive development setup with automated code formatting, linting, and quality checks to ensure consistent code style and prevent common errors.\n\n### Development Tools Setup\n\nThe project is configured with modern development tools for the best developer experience:\n\n#### Code Quality Tools\n\n- **Prettier**: Simple, standard code formatting with Tailwind CSS class sorting\n- **ESLint**: Minimal linting with Next.js and TypeScript defaults\n- **TypeScript**: Type checking for build validation\n- **Husky**: Git hooks for automated quality checks\n\n#### IDE Configuration\n\nPre-configured VSCode/Cursor settings for optimal development:\n\n- Format on save enabled\n- Auto-fix ESLint issues on save\n- Tailwind CSS IntelliSense support\n- TypeScript IntelliSense and error highlighting\n- Recommended extensions list\n\n#### Git Hooks\n\nAutomated quality checks run on every commit and push:\n\n- **Pre-commit**: Runs linting and formatting on staged files\n- **Pre-push**: Runs TypeScript checking and build verification\n\n### Available Scripts\n\n```bash\n# Development\nnpm run dev          # Start development server with hot reload\nnpm run build        # Build for production\nnpm run start        # Start production server\n\n# Code Quality\nnpm run lint         # Check code with ESLint\nnpm run lint:fix     # Fix ESLint issues automatically\nnpm run format       # Format code with Prettier\nnpm run format:check # Check if code is properly formatted\nnpm run typecheck    # Type check with TypeScript compiler\n\n# Git Hooks (handled automatically)\nnpm run prepare      # Initialize Husky (runs on npm install)\n```\n\n### IDE Setup (VSCode/Cursor)\n\nThe project includes `.vscode/` configuration with:\n\n#### Recommended Extensions\n\n- **Prettier**: Code formatting\n- **ESLint**: Code linting\n- **Tailwind CSS IntelliSense**: CSS class completion\n- **Code Spell Checker**: Spelling validation\n- **Error Lens**: Inline error display\n- **Auto Rename Tag**: Automatic HTML/JSX tag renaming\n\n#### Editor Settings\n\n- **Auto-format on save** for consistent code style\n- **Auto-fix ESLint issues** to prevent common errors\n- **Tailwind class sorting** for better organization\n- **TypeScript hints** for better development experience\n\n### First-Time Setup for New Developers\n\n1. **Clone and install dependencies**:\n\n   ```bash\n   git clone https://github.com/mostafa-drz/nextjs-dify-firebase-starter.git\n   cd nextjs-dify-firebase-starter\n   npm install\n   ```\n\n2. **Open in VSCode/Cursor**:\n\n   ```bash\n   code .  # or cursor .\n   ```\n\n3. **Install recommended extensions** when prompted\n\n4. **Configure environment** (see Environment Configuration section)\n\n5. **Verify setup**:\n   ```bash\n   npm run typecheck  # Should pass without errors\n   npm run lint       # Should pass without errors\n   npm run build      # Should build successfully\n   ```\n\n### Code Formatting Rules\n\nThe project uses minimal, standard formatting conventions:\n\n- **Print width**: 100 characters\n- **Single quotes** for strings\n- **Semicolons** required\n- **2 spaces** for indentation\n- **Tailwind classes** automatically sorted\n\n### Quality Checks\n\nBefore every commit, the following checks run automatically:\n\n1. **ESLint**: Checks for code quality issues\n2. **Prettier**: Ensures consistent formatting\n3. **TypeScript**: Validates type safety\n\nBefore every push:\n\n1. **TypeScript compilation**: Ensures no type errors\n2. **Production build**: Ensures the app builds successfully\n\n### Troubleshooting\n\n**Husky hooks not working?**\n\n```bash\nnpx husky install\n```\n\n**ESLint/Prettier conflicts?**\nThe project uses `eslint-config-prettier` to disable conflicting rules automatically.\n\n**TypeScript errors on build?**\n\n```bash\nnpm run typecheck  # Check specific TypeScript issues\n```\n\n**Extensions not working in Cursor?**\nCursor is compatible with VSCode extensions. Install the recommended extensions manually if auto-prompt doesn't appear.\n\n## 🎯 Usage\n\n### Basic Integration\n\nUse the `DifyChat` component in your pages:\n\n```tsx\nimport { DifyChat } from '@/components/dify/DifyChat';\n\nexport default function MyPage() {\n  return (\n    \u003cDifyChat\n      apiKey=\"app-your-dify-key\" // Server-side only, never exposed\n      name=\"My Assistant\"\n      placeholder=\"Ask me anything...\"\n      welcomeMessage=\"Hello! How can I help you today?\"\n    /\u003e\n  );\n}\n```\n\n### Streaming Chat (New!)\n\nEnable real-time streaming for instant message updates:\n\n```tsx\nimport { DifyChat } from '@/components/dify/DifyChat';\n\nexport default function StreamingPage() {\n  return (\n    \u003cDifyChat\n      name=\"Streaming Assistant\"\n      enableStreaming={true}\n      streamingMode=\"auto\"\n      placeholder=\"Ask me anything with real-time streaming...\"\n      welcomeMessage=\"Hello! Watch my responses appear in real-time!\"\n    /\u003e\n  );\n}\n```\n\n**Streaming Features:**\n\n- ✅ **Real-time message updates** - See responses as they're generated\n- ✅ **Production-ready error handling** - Automatic retry with exponential backoff\n- ✅ **Proper cleanup** - AbortController prevents memory leaks\n- ✅ **Stop functionality** - Users can stop streaming at any time\n- ✅ **Fallback support** - Gracefully falls back to blocking mode on errors\n- ✅ **Configurable** - Choose between auto-streaming or manual control\n\n### Credit Management\n\nAccess credit information using the `useCredits` hook:\n\n```tsx\nimport { useCredits } from '@/lib/hooks/useCredits';\n\nexport function MyComponent() {\n  const { availableCredits, hasEnoughCredits, deductForTokens } = useCredits();\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eAvailable: {availableCredits} credits\u003c/p\u003e\n      {!hasEnoughCredits(10) \u0026\u0026 \u003cp\u003eInsufficient credits!\u003c/p\u003e}\n    \u003c/div\u003e\n  );\n}\n```\n\n### Server Actions\n\nUse server actions for secure Dify API calls:\n\n```tsx\nimport { sendDifyMessage } from '@/lib/actions/dify';\n\n// In a server action or API route\nconst result = await sendDifyMessage(userId, apiKey, {\n  query: 'Hello',\n  user: userId,\n  response_mode: 'blocking',\n});\n\nif (result.success) {\n  console.log('Response:', result.data?.answer);\n  console.log('Tokens used:', result.usage?.total_tokens);\n}\n```\n\n## 💬 Conversation Management\n\nThis boilerplate implements a **client-side conversation management system** using React Query for caching and optimistic updates. This approach prioritizes simplicity and performance while providing a solid foundation for developers to extend with their own persistence strategies.\n\n### Architecture Overview\n\n**Why React Query?**\n\n- **Automatic caching** with intelligent invalidation\n- **Optimistic updates** for instant UI feedback\n- **Background refetching** to keep data fresh\n- **Error handling** with retry logic\n- **DevTools** for debugging (development only)\n\n**Why Not Firebase/Firestore?**\n\n- **Simplicity**: Avoids additional database complexity\n- **Performance**: Client-side caching is faster than database queries\n- **Flexibility**: Developers can choose their own persistence layer\n- **Cost**: Reduces Firebase read/write operations\n\n### Data Flow\n\n```\nUser Action → Optimistic Update → API Call → Cache Update → UI Update\n     ↓              ↓                ↓           ↓           ↓\n  Click Send → Show Message → Call Dify → Update Cache → Show Response\n```\n\n### Usage Examples\n\n#### Basic Conversation Management\n\n```tsx\nimport { useConversationMessages } from '@/lib/hooks/useConversationMessages';\n\nexport function ChatComponent() {\n  const { messages, isLoading, addMessageOptimistically, invalidate } = useConversationMessages(\n    conversationId,\n    userId,\n    apiKey\n  );\n\n  const handleSendMessage = async (content: string) =\u003e {\n    const tempMessage = { id: 'temp', content, role: 'user' };\n    addMessageOptimistically(tempMessage); // Instant UI update\n\n    const result = await sendDifyMessage(userId, apiKey, { query: content });\n    // Cache automatically updated with real data\n  };\n\n  return (\n    \u003cdiv\u003e\n      {isLoading \u0026\u0026 \u003cdiv\u003eLoading conversation...\u003c/div\u003e}\n      {messages.map((message) =\u003e (\n        \u003cdiv key={message.id}\u003e{message.content}\u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n}\n```\n\n#### Conversation List Management\n\n```tsx\nimport { ConversationList } from '@/components/dify/ConversationList';\n\nexport function ChatPage() {\n  const [currentConversationId, setCurrentConversationId] = useState\u003cstring\u003e();\n\n  return (\n    \u003cdiv className=\"grid gap-8 lg:grid-cols-4\"\u003e\n      \u003cdiv className=\"lg:col-span-1\"\u003e\n        \u003cConversationList\n          apiKey=\"app-demo-key\"\n          userId={user.uid}\n          currentConversationId={currentConversationId}\n          onConversationSelect={setCurrentConversationId}\n          onCreateNew={() =\u003e setCurrentConversationId(undefined)}\n        /\u003e\n      \u003c/div\u003e\n      \u003cdiv className=\"lg:col-span-3\"\u003e\n        \u003cDifyChat\n          apiKey=\"app-demo-key\"\n          conversationId={currentConversationId}\n          // ... other props\n        /\u003e\n      \u003c/div\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Performance Features\n\n- **Smart Caching**: 5-minute cache with 1-minute stale time\n- **Background Refetching**: Keep data fresh without user interaction\n- **Prefetching**: Preload messages on conversation hover\n- **Memory Management**: Automatic garbage collection of unused data\n- **Bundle Size**: React Query adds only ~13KB gzipped\n\n### Extending the System\n\n#### Option 1: Add Firebase Persistence\n\n```tsx\n// Add to your Firebase functions\nexport const syncConversationToFirestore = async (conversationId: string, messages: unknown[]) =\u003e {\n  await db.collection('conversations').doc(conversationId).set({\n    messages,\n    lastUpdated: new Date(),\n    userId: auth.currentUser?.uid,\n  });\n};\n\n// Call after successful message send\nconst result = await sendDifyMessage(userId, apiKey, request);\nawait syncConversationToFirestore(result.data.conversation_id, messages);\n```\n\n#### Option 2: Add Local Storage Backup\n\n```tsx\n// Add to useConversationMessages hook\nuseEffect(() =\u003e {\n  if (data) {\n    localStorage.setItem(`conversation-${conversationId}`, JSON.stringify(data));\n  }\n}, [data, conversationId]);\n```\n\n#### Option 3: Add Real-time Sync\n\n```tsx\n// Add WebSocket or Server-Sent Events\nconst useRealtimeMessages = (conversationId: string) =\u003e {\n  useEffect(() =\u003e {\n    const ws = new WebSocket(`/ws/conversations/${conversationId}`);\n    ws.onmessage = (event) =\u003e {\n      const newMessage = JSON.parse(event.data);\n      addMessageOptimistically(newMessage);\n    };\n    return () =\u003e ws.close();\n  }, [conversationId]);\n};\n```\n\n### Debug Tools\n\nReact Query DevTools are automatically enabled in development:\n\n```tsx\n// Automatically included in development builds\nimport { ReactQueryDevtools } from '@tanstack/react-query-devtools';\n```\n\n### Best Practices\n\n**Do's:**\n\n- ✅ Use optimistic updates for better UX\n- ✅ Implement proper error boundaries\n- ✅ Add loading states for all async operations\n- ✅ Use TypeScript for type safety\n- ✅ Test with React Query DevTools\n\n**Don'ts:**\n\n- ❌ Don't bypass the cache for real-time updates\n- ❌ Don't store sensitive data in client-side cache\n- ❌ Don't forget to handle offline scenarios\n- ❌ Don't over-fetch data (use pagination)\n\n## 🏗️ Project Structure\n\n```\nsrc/\n├── app/                    # Next.js App Router pages\n│   ├── chat/              # Chat demo page with conversation management\n│   ├── conversations/     # Dedicated conversation management page\n│   ├── dashboard/         # User dashboard\n│   ├── login/            # Authentication page\n│   └── test-credits/     # Credit testing utilities\n├── components/\n│   ├── auth/             # Authentication components\n│   ├── credits/          # Credit management UI\n│   ├── dify/            # Dify integration components\n│   │   ├── DifyChat.tsx           # Main chat interface\n│   │   ├── ConversationList.tsx  # Conversation management\n│   │   ├── MessageFeedback.tsx   # Message feedback system\n│   │   └── SuggestedQuestions.tsx # Suggested questions\n│   ├── providers/        # React context providers\n│   │   └── QueryProvider.tsx     # React Query provider\n│   └── ui/              # shadcn/ui components\n├── lib/\n│   ├── actions/         # Server actions\n│   ├── hooks/           # Custom React hooks\n│   │   ├── useCredits.ts              # Credit management\n│   │   └── useConversationMessages.ts # Conversation caching\n│   ├── services/        # Dify API services\n│   │   └── dify/        # Modular Dify service architecture\n│   ├── utils/           # Utility functions\n│   └── config/          # Configuration constants\n└── types/               # TypeScript type definitions\n```\n\n## 🔧 Configuration\n\n### Credit System\n\nConfigure credit costs and limits in `src/lib/config/constants.ts`:\n\n```typescript\nexport const CREDIT_CONFIG = {\n  TOKENS_PER_CREDIT: 1000, // 1 credit = 1000 tokens\n  FREE_TIER_CREDITS: 100, // Free credits per month\n  MIN_CREDITS_WARNING: 10, // Show warning below this\n  CREDIT_PURCHASE_AMOUNTS: [10, 50, 100, 500],\n} as const;\n```\n\n### Dify Apps\n\nFor multiple Dify apps, create an app configuration:\n\n```typescript\nconst DIFY_APPS = {\n  chat: {\n    name: 'Chat Assistant',\n    apiKey: process.env.DIFY_CHAT_API_KEY!,\n  },\n  summarizer: {\n    name: 'Document Summarizer',\n    apiKey: process.env.DIFY_SUMMARIZER_API_KEY!,\n  },\n};\n```\n\n## 🧪 Testing\n\n### Testing Philosophy\n\nThis project follows focused, self-descriptive testing principles that prioritize quality over quantity. Our tests focus on essential business logic and real-world scenarios rather than exhaustive coverage.\n\n**Core Principles:**\n\n- **Self-Descriptive**: Test names clearly describe what's being tested and expected outcomes\n- **Essential Focus**: Test business-critical logic first (credit system, authentication, payment flows)\n- **Not Exhaustive**: Skip trivial functions, third-party libraries, and implementation details\n- **Real-World Scenarios**: Test user journeys and integration points where things can break\n- **Maintainable**: Simple, focused tests that are easy to understand and modify\n\n**What We Test:**\n\n- ✅ Business logic (credit calculations, user authentication flows)\n- ✅ Error handling and failure scenarios\n- ✅ Integration points between different parts of the system\n- ✅ User journeys and complete workflows\n- ✅ Edge cases and boundary conditions\n\n**What We Don't Test:**\n\n- ❌ Third-party libraries (Firebase SDK, Dify API)\n- ❌ Simple utilities and data transformations\n- ❌ Configuration and environment variables\n- ❌ Styling and visual appearance\n- ❌ Trivial getters/setters without business logic\n\n### Run Tests\n\n```bash\nnpm test              # Run all tests\nnpm test:watch        # Run tests in watch mode\nnpm test:coverage     # Run tests with coverage report\nnpm test:ui           # Run tests with UI interface\nnpm test:run          # Run tests once (CI mode)\nnpm test:ci           # Run tests with coverage and verbose output\nnpm test:firebase     # Run tests with Firebase emulators\nnpm test:dify         # Test Dify API connection\n```\n\n### Test Coverage\n\nOur test suite covers:\n\n- ✅ **Business Logic**: Credit calculations, user authentication, rate limiting\n- ✅ **Server Actions**: Credit management, user initialization, Dify API integration\n- ✅ **Utility Functions**: Credit utilities, input validation, rate limiting\n- ✅ **Dify Services**: Chat service, conversation management, API integration\n- ✅ **React Hooks**: useCredits, useChatMessages, useDify integration\n- ✅ **Error Handling**: Database errors, API failures, network issues\n- ✅ **Edge Cases**: Insufficient credits, rate limit exceeded, invalid inputs\n\n### Test Structure\n\n```\nsrc/\n├── __tests__/\n│   ├── setup.ts              # Test environment setup\n│   ├── mocks/                # Mock implementations\n│   │   ├── handlers.ts       # MSW API handlers\n│   │   ├── firebase-admin.ts # Firebase Admin mocks\n│   │   └── firebase-client.ts# Firebase Client mocks\n│   ├── fixtures/             # Test data fixtures\n│   │   ├── users.ts          # User test data\n│   │   └── dify-responses.ts # Dify API response mocks\n│   └── utils/                # Test utilities\n│       ├── render.tsx        # Custom render function\n│       └── auth.ts           # Auth test helpers\n├── lib/\n│   ├── actions/__tests__/    # Server action tests\n│   ├── hooks/__tests__/      # React hook tests\n│   ├── services/dify/__tests__/ # Dify service tests\n│   └── utils/__tests__/      # Utility function tests\n```\n\n### Test Credit System\n\nVisit `/test-credits` to test credit deduction and management.\n\n### Test Dify Integration\n\nVisit `/chat` to test the Dify chat interface.\n\n### Test Sentry Integration\n\nVisit `/sentry-test` to test error tracking and logging.\n\n### Enable Google Analytics\n\n1. Enable Analytics in your Firebase project console\n2. Copy the Measurement ID from Analytics settings\n3. Add `NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX` to `.env.local`\n\n## 🌍 Adding More Languages\n\nThis boilerplate supports internationalization using next-intl. Currently configured for English only, but you can easily add more languages:\n\n### Adding a New Language (e.g., Spanish)\n\n1. **Add locale to config:**\n\n   ```typescript\n   // src/i18n/config.ts\n   export const locales = ['en', 'es'] as const;\n   ```\n\n2. **Create translation file:**\n\n   ```bash\n   # Create src/i18n/messages/es.json\n   {\n     \"common\": {\n       \"loading\": \"Cargando...\",\n       \"error\": \"Ocurrió un error\"\n     },\n     \"chat\": {\n       \"title\": \"Asistente de Chat IA\",\n       \"placeholder\": \"Escribe tu mensaje...\"\n     }\n   }\n   ```\n\n3. **Update middleware:**\n\n   ```typescript\n   // middleware.ts\n   export const config = {\n     matcher: ['/', '/(en|es)/:path*'],\n   };\n   ```\n\n4. **Add language switcher component** (optional)\n\n### Context Integration\n\nThe system automatically passes user language context to Dify AI for smarter responses:\n\n```typescript\n// Language context is automatically included\nconst context = {\n  language: { code: 'es', locale: 'es-ES' },\n  timestamp: '2024-12-19T10:30:00Z',\n  timezone: 'Europe/Madrid',\n};\n```\n\nThis helps the AI provide responses in the user's preferred language and cultural context.\n\n## 🚀 Deployment\n\n### Vercel (Recommended)\n\n1. Push your code to GitHub\n2. Connect repository to [Vercel](https://vercel.com)\n3. Add environment variables in Vercel dashboard\n4. Deploy\n\n### Other Platforms\n\nThis Next.js app can be deployed to any platform supporting Node.js:\n\n- Railway\n- Render\n- Heroku\n- DigitalOcean App Platform\n- AWS Amplify\n\n## 📊 Monitoring\n\n### Firebase Console\n\n- Monitor authentication metrics\n- View Firestore usage and costs\n- Check security rule violations\n\n### Sentry Error Tracking\n\nThis project includes production-ready **Sentry integration** with minimal but essential logging:\n\n#### Features\n\n- **Smart Error Filtering**: Automatically filters non-critical errors (network timeouts, browser quirks)\n- **Privacy-First**: Masks sensitive data, excludes cookies and IP addresses\n- **Performance Monitoring**: Tracks slow operations and API performance\n- **Production Optimized**: Lower sampling rates to reduce noise (10% traces, 1% sessions)\n\n#### Setup\n\n1. Create a free [Sentry account](https://sentry.io) and project\n2. Copy your DSN and add to `.env.local`:\n   ```bash\n   NEXT_PUBLIC_SENTRY_DSN=https://your_key@o0.ingest.sentry.io/0\n   SENTRY_DSN=https://your_key@o0.ingest.sentry.io/0\n   ```\n3. Test with `/sentry-test` page\n\n#### Usage Examples\n\n```typescript\nimport { logError, logMessage, LogLevel } from '@/lib/sentry';\n\n// Log critical errors\ntry {\n  await processPayment();\n} catch (error) {\n  logError(error, { userId, amount, paymentMethod });\n}\n\n// Log important events\nlogMessage('User upgraded to premium', LogLevel.INFO);\n```\n\n#### What Gets Logged\n\n- ✅ API errors (5xx responses)\n- ✅ Authentication failures\n- ✅ Payment processing errors\n- ✅ Slow operations (\u003e3s)\n- ✅ Unhandled exceptions\n- ❌ Network timeouts (filtered)\n- ❌ Browser extension errors (filtered)\n- ❌ Expected auth errors (filtered)\n\n### Application Monitoring\n\n- Credit usage patterns in Firestore\n- Real-time error alerts and performance monitoring\n- User activity via Firebase Analytics\n\n### Google Analytics Integration\n\nThis project includes **privacy-first Google Analytics** using Firebase Analytics with minimal data collection:\n\n#### Features\n\n- **Production Only**: Analytics only tracks in production environment\n- **Essential Events**: Tracks only business-critical events (auth, chat, credits)\n- **Privacy Focused**: No personal data collection or tracking\n- **Client-Side Only**: Simple Firebase Analytics integration\n\n#### Tracked Events\n\n- ✅ **Page Views**: User navigation patterns\n- ✅ **Authentication**: Login/logout events\n- ✅ **Chat Usage**: Message sending and conversation starts\n- ✅ **Credit Usage**: Purchase and deduction events\n- ✅ **External Links**: Outbound link clicks\n\n#### Setup\n\n1. **Enable Analytics** in your [Firebase Console](https://console.firebase.google.com)\n2. **Copy Measurement ID** from Analytics → Data Streams\n3. **Add to Environment**: `NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX`\n4. **Deploy**: Analytics will automatically start tracking in production\n\n#### Usage Examples\n\n```typescript\nimport { trackAuth, trackChat, trackCredits } from '@/lib/analytics';\n\n// Track user authentication\ntrackAuth('login');\n\n// Track chat interactions\ntrackChat('message_sent', messageLength);\n\n// Track credit events\ntrackCredits('purchase', amount);\n```\n\n#### Privacy Compliance\n\n- **GDPR Compliant**: No personal data collection\n- **Development Safe**: No tracking in development environment\n- **Error Handling**: Graceful failures without breaking user experience\n\n## 🔐 Authentication System\n\nThis project uses **HTTP-only cookie authentication** for secure Firebase integration. No manual token handling required!\n\n### How It Works\n\n1. **User signs in** → Firebase client gets ID token\n2. **Token sent to server** → `/api/auth/set-token` sets HTTP-only cookie\n3. **Automatic authentication** → Cookie sent with every request\n4. **User signs out** → Cookie cleared via `/api/auth/clear-token`\n\n### Security Features\n\n- ✅ **HTTP-only cookies** - XSS protection\n- ✅ **HTTPS only** - Secure in production\n- ✅ **SameSite=strict** - CSRF protection\n- ✅ **Proper JWT verification** - Firebase Admin SDK\n- ✅ **7-day expiry** - Reasonable session length\n\n### Files\n\n- `src/lib/config/auth-config.ts` - Simple constants\n- `src/app/api/auth/set-token/route.ts` - Set cookie\n- `src/app/api/auth/clear-token/route.ts` - Clear cookie\n- `src/lib/utils/auth-cookie.ts` - Cookie helpers\n- `src/lib/auth/middleware-auth.ts` - JWT verification\n\n## 🛡️ Security Considerations\n\n1. **Authentication**: HTTP-only cookies with proper JWT verification\n2. **API Keys**: Never expose Dify API keys to client-side code\n3. **Credit Limits**: Implement proper credit limits to prevent abuse\n4. **Rate Limiting**: Consider adding rate limiting for API calls\n5. **User Validation**: Always validate user authentication server-side\n6. **Firestore Rules**: Keep security rules restrictive and test thoroughly\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests if applicable\n5. Submit a pull request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🆘 Support\n\nFor support and questions:\n\n- Create an issue in this repository\n- Email: support@yourdomain.com\n- Check the [Dify Documentation](https://docs.dify.ai/)\n- Review [Firebase Documentation](https://firebase.google.com/docs)\n\n## 📚 Additional Resources\n\n- **[Dify API Documentation](./difyDocs/)** - Complete API reference and integration guides\n- **[Demo Applications](./demos/)** - Example apps showcasing Dify capabilities\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmostafa-drz%2Fnextjs-dify-firebase-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmostafa-drz%2Fnextjs-dify-firebase-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmostafa-drz%2Fnextjs-dify-firebase-starter/lists"}