Frontend Setup
Complete guide to setting up and running the React frontend
Frontend Setup
The SynapseAI frontend is a modern React application built with Vite, TanStack Router, and TanStack Query. It provides a chat-based interface for B2B ordering, user authentication, and real-time voice chat capabilities. The demo uses FlavorFlux branding.
Prerequisites
- Node.js 20.x or higher
- pnpm package manager
- Backend API running (see Backend Setup)
Installation
Install pnpm
If you don't have pnpm installed:
# Using npm
npm install -g pnpm
# Using Homebrew (macOS)
brew install pnpm
# Using curl
curl -fsSL https://get.pnpm.io/install.sh | sh -Install Dependencies
cd frontend
pnpm installConfiguration
Environment Variables
Create a .env file in the frontend directory:
cd frontend
cp .env.example .envConfigure the following variables:
# Backend API URL
VITE_API_BASE_URL=http://localhost:8001
# WhatsApp Integration (optional)
VITE_WHATSAPP_PHONE_NUMBER_ID=your-phone-number-id
VITE_WHATSAPP_ACCESS_TOKEN=your-access-token
VITE_WHATSAPP_VERIFY_TOKEN=your-verify-token
# Feature Flags
VITE_ENABLE_VOICE_CHAT=true
VITE_ENABLE_WHATSAPP=falseRunning the Frontend
Development Mode
Start the development server with hot reload:
cd frontend
pnpm devThe application will be available at http://localhost:5173
Building for Production
Create an optimized production build:
cd frontend
pnpm buildThe built files will be in the dist/ directory.
Preview Production Build
Preview the production build locally:
cd frontend
pnpm previewProject Structure
frontend/
├── api/ # WhatsApp API serverless functions
│ ├── whatsapp-auth.ts
│ ├── whatsapp-webhook.ts
│ └── types/
├── public/ # Static assets
│ ├── images/
│ └── manifest.json
├── src/
│ ├── components/ # React components
│ │ ├── agent-selector.tsx
│ │ ├── chat-empty-state.tsx
│ │ ├── chat-header.tsx
│ │ ├── chat-input.tsx
│ │ ├── chat-interface.tsx
│ │ ├── chat-message.tsx
│ │ ├── message-avatar.tsx
│ │ ├── voice-widget.tsx
│ │ ├── user-profile.tsx
│ │ ├── auth/ # Authentication components
│ │ │ ├── auth-form-footer.tsx
│ │ │ └── password-field.tsx
│ │ └── ui/ # Shadcn/ui components
│ ├── hooks/ # Custom React hooks
│ │ ├── use-auth-form.ts
│ │ ├── use-autoscroll.ts
│ │ ├── use-chat.ts
│ │ ├── use-me.ts
│ │ ├── use-mobile.ts
│ │ └── voice/ # Voice chat hooks
│ ├── integrations/ # API integrations
│ │ ├── auth-api.ts
│ │ ├── chat-api.ts
│ │ └── tanstack-query/
│ ├── lib/ # Utilities and helpers
│ │ ├── agent-templates.ts
│ │ ├── auth-schemas.ts
│ │ └── utils.ts
│ ├── routes/ # TanStack Router routes
│ │ ├── __root.tsx
│ │ ├── index.tsx
│ │ └── auth/
│ ├── store/ # State management
│ │ ├── auth.ts
│ │ ├── auth-ui.ts
│ │ └── chat.ts
│ ├── types/ # TypeScript types
│ ├── main.tsx # Application entry point
│ └── styles.css # Global styles
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
└── vercel.json # Vercel deployment configKey Features
🎨 Modern UI
Built with:
- Shadcn/ui: Beautiful, accessible component library
- Tailwind CSS: Utility-first CSS framework
- Radix UI: Unstyled, accessible component primitives
🔐 Authentication
Secure authentication with:
- Email/password login
- JWT token management
- Automatic token refresh
- Protected routes
💬 Chat Interface
Real-time conversational interface:
- Message history
- Typing indicators
- Auto-scroll behavior
- Suggested actions
- Product disambiguation UI
🎤 Voice Chat
WebRTC-based voice chat:
- Real-time audio streaming
- Audio level monitoring
- Voice activity detection
- OpenAI Realtime API integration
📱 WhatsApp Integration
Connect with customers via WhatsApp:
- Webhook handling
- Message sending/receiving
- Authentication flow
- Media support
Development
Adding Components
The project uses Shadcn/ui for components. Add new components:
pnpm dlx shadcn@latest add button
pnpm dlx shadcn@latest add dialog
pnpm dlx shadcn@latest add dropdown-menuRouting
The project uses TanStack Router with file-based routing:
- Create a new file in
src/routes/:
// src/routes/products.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/products')({
component: Products,
})
function Products() {
return <div>Products Page</div>
}- The route will automatically be available at
/products
State Management
The project uses TanStack Store for state management:
Example: Auth Store (src/store/auth.ts):
import { Store } from '@tanstack/store'
export const authStore = new Store({
user: null,
token: null,
isAuthenticated: false,
})API Integration
API calls use TanStack Query for data fetching:
Example: Chat API (src/integrations/chat-api.ts):
import { useMutation } from '@tanstack/react-query'
export function useSendMessage() {
return useMutation({
mutationFn: async (message: string) => {
const response = await fetch('/agent/chat', {
method: 'POST',
body: JSON.stringify({ message }),
})
return response.json()
},
})
}Styling
The project uses Tailwind CSS. Customize styles in:
tailwind.config.js- Tailwind configurationsrc/styles.css- Global styles- Component files - Component-specific styles
Example:
<div className="flex items-center gap-4 p-4 bg-background rounded-lg">
<Button variant="default">Submit</Button>
</div>Testing
Unit Tests
Run unit tests with Vitest:
pnpm testWatch mode:
pnpm test:watchE2E Tests
End-to-end tests (if configured):
pnpm test:e2eBuilding for Production
Standard Build
pnpm buildOutput in dist/ directory.
Deployment
The frontend is configured for deployment on Vercel:
- Connect Repository: Link your GitHub repository to Vercel
- Configure Build:
- Build Command:
pnpm build - Output Directory:
dist
- Build Command:
- Set Environment Variables: Add your
.envvariables in Vercel dashboard - Deploy: Vercel will automatically deploy on push to main
Alternative deployment targets:
- Netlify: Similar to Vercel
- AWS S3 + CloudFront: Static hosting
- Docker: Use included Dockerfile
Docker Build
cd frontend
docker build -t b2b-frontend .
docker run -p 3000:80 b2b-frontendWhatsApp Integration
Setup
-
Create WhatsApp Business Account:
- Visit Meta for Developers
- Create a WhatsApp Business App
-
Configure Webhook:
- Webhook URL:
https://your-domain.com/api/whatsapp-webhook - Verify Token: Set in
VITE_WHATSAPP_VERIFY_TOKEN
- Webhook URL:
-
Deploy API Functions:
- The
api/directory contains serverless functions - Deploy to Vercel automatically
- The
-
Test Integration:
- Send a message to your WhatsApp number
- Check webhook logs in Vercel
WhatsApp API Functions
Authentication (api/whatsapp-auth.ts):
- Handles OAuth flow
- Manages tokens
Webhook (api/whatsapp-webhook.ts):
- Receives messages
- Sends responses
- Handles events
Verification (api/whatsapp-verify.ts):
- Verifies webhook requests
Voice Chat Setup
Requirements
- OpenAI API Key: For Realtime API
- HTTPS: WebRTC requires secure connection
Configuration
VITE_ENABLE_VOICE_CHAT=true
OPENAI_API_KEY=sk-...
OPENAI_REALTIME_MODEL=gpt-4o-realtime-preview-2024-10-01Usage
- Click the voice icon in the chat interface
- Allow microphone access
- Start speaking
- Receive real-time voice responses
Common Issues
Issue: "Cannot connect to backend"
Solution:
- Verify backend is running:
curl http://localhost:8001/health - Check
VITE_API_BASE_URLin.env - Ensure CORS is configured in backend
Issue: "Module not found"
Solution:
# Clear node_modules and reinstall
rm -rf node_modules pnpm-lock.yaml
pnpm installIssue: "Build fails with TypeScript errors"
Solution:
# Check TypeScript configuration
pnpm tsc --noEmit
# Fix any type errors
# Update tsconfig.json if neededIssue: "Voice chat not working"
Solution:
- Check HTTPS is enabled (required for WebRTC)
- Verify microphone permissions
- Check OpenAI API key is valid
- Review browser console for errors
Performance Optimization
Code Splitting
TanStack Router automatically code-splits routes:
// Lazy load heavy components
const HeavyComponent = lazy(() => import('./HeavyComponent'))Image Optimization
Optimize images before adding to public/:
# Using ImageOptim, TinyPNG, or similar toolsBundle Analysis
Analyze bundle size:
pnpm build -- --analyzeLinting and Formatting
ESLint
Run linter:
pnpm lintFix automatically:
pnpm lint:fixPrettier
Format code:
pnpm formatNext Steps
- Backend Setup - Connect to the backend API
- Architecture - Understand the system design
- User Scenarios - Learn about user workflows
- Deployment - Deploy to production