Welcome

Introduction

Introduction

Setup & Installation

Architecture & Design

Architecture

Features & Scenarios

Deployment

Deployment

API Reference

API Reference

Tools & Utilities

Scripts & UtilitiesTroubleshooting

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 install

Configuration

Environment Variables

Create a .env file in the frontend directory:

cd frontend
cp .env.example .env

Configure 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=false

Running the Frontend

Development Mode

Start the development server with hot reload:

cd frontend
pnpm dev

The application will be available at http://localhost:5173

Building for Production

Create an optimized production build:

cd frontend
pnpm build

The built files will be in the dist/ directory.

Preview Production Build

Preview the production build locally:

cd frontend
pnpm preview

Project 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 config

Key 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-menu

Routing

The project uses TanStack Router with file-based routing:

  1. 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>
}
  1. 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 configuration
  • src/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 test

Watch mode:

pnpm test:watch

E2E Tests

End-to-end tests (if configured):

pnpm test:e2e

Building for Production

Standard Build

pnpm build

Output in dist/ directory.

Deployment

The frontend is configured for deployment on Vercel:

  1. Connect Repository: Link your GitHub repository to Vercel
  2. Configure Build:
    • Build Command: pnpm build
    • Output Directory: dist
  3. Set Environment Variables: Add your .env variables in Vercel dashboard
  4. 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-frontend

WhatsApp Integration

Setup

  1. Create WhatsApp Business Account:

    • Visit Meta for Developers
    • Create a WhatsApp Business App
  2. Configure Webhook:

    • Webhook URL: https://your-domain.com/api/whatsapp-webhook
    • Verify Token: Set in VITE_WHATSAPP_VERIFY_TOKEN
  3. Deploy API Functions:

    • The api/ directory contains serverless functions
    • Deploy to Vercel automatically
  4. 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-01

Usage

  1. Click the voice icon in the chat interface
  2. Allow microphone access
  3. Start speaking
  4. 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_URL in .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 install

Issue: "Build fails with TypeScript errors"

Solution:

# Check TypeScript configuration
pnpm tsc --noEmit

# Fix any type errors
# Update tsconfig.json if needed

Issue: "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 tools

Bundle Analysis

Analyze bundle size:

pnpm build -- --analyze

Linting and Formatting

ESLint

Run linter:

pnpm lint

Fix automatically:

pnpm lint:fix

Prettier

Format code:

pnpm format

Next Steps

  • Backend Setup - Connect to the backend API
  • Architecture - Understand the system design
  • User Scenarios - Learn about user workflows
  • Deployment - Deploy to production

On this page

Frontend SetupPrerequisitesInstallationInstall pnpmInstall DependenciesConfigurationEnvironment VariablesRunning the FrontendDevelopment ModeBuilding for ProductionPreview Production BuildProject StructureKey Features🎨 Modern UI🔐 Authentication💬 Chat Interface🎤 Voice Chat📱 WhatsApp IntegrationDevelopmentAdding ComponentsRoutingState ManagementAPI IntegrationStylingTestingUnit TestsE2E TestsBuilding for ProductionStandard BuildDeploymentDocker BuildWhatsApp IntegrationSetupWhatsApp API FunctionsVoice Chat SetupRequirementsConfigurationUsageCommon IssuesIssue: "Cannot connect to backend"Issue: "Module not found"Issue: "Build fails with TypeScript errors"Issue: "Voice chat not working"Performance OptimizationCode SplittingImage OptimizationBundle AnalysisLinting and FormattingESLintPrettierNext Steps