Advanced Topics

Deep dive into architecture, performance optimization, security best practices, and troubleshooting.

Sections

Architecture Overview

InAppAI React uses a backend-first security model:

┌──────────────────────────────┐
│      Browser (Public)        │
│                              │
│  • No API keys               │
│  • No secrets                │
│  • JWT auth only             │
│  • Tool handlers run here    │
└──────────────┬───────────────┘
               │ HTTPS
┌──────────────────────────────┐
│    Backend (Protected)       │
│                              │
│  • API keys stored           │
│  • Validates all requests    │
│  • Rate limiting             │
│  • User authentication       │
└──────────────┬───────────────┘
               │ API Key
┌──────────────────────────────┐
│      AI Provider API         │
└──────────────────────────────┘

Core Principles

  1. Controlled Mode - You manage message state, giving full control over persistence and state management
  2. Backend Separation - All AI API calls go through your backend, never exposing API keys to the browser
  3. Client-Side Tools - Tool handlers run in the browser, keeping your app responsive

Data Flow

  1. User types a message in the chat
  2. Component calls onMessagesChange with updated messages
  3. Message is sent to your backend via the endpoint
  4. Backend validates request and calls AI provider
  5. AI response is returned through onMessagesChange
  6. If AI wants to call a tool, handler executes locally
  7. Tool result is sent back through the message flow

Performance Tips

Bundle Size

InAppAI React is approximately ~95KB minified (~30KB gzipped).

Lazy load for better initial page load:

import { lazy, Suspense } from 'react';

const InAppAI = lazy(() =>
  import('@inappai/react').then(m => ({ default: m.InAppAI }))
);

function App() {
  return (
    <Suspense fallback={<div>Loading chat...</div>}>
      <InAppAI {...props} />
    </Suspense>
  );
}

Message State Optimization

Limit message history for large conversations:

const MAX_MESSAGES = 100;

const displayedMessages = messages.slice(-MAX_MESSAGES);

<InAppAI
  messages={displayedMessages}
  onMessagesChange={setMessages}
/>

Memoize callbacks:

const handleMessagesChange = useCallback((newMessages: Message[]) => {
  setMessages(newMessages);
}, []);

<InAppAI onMessagesChange={handleMessagesChange} />

Context Optimization

Memoize context for static data:

const context = useMemo(() => ({
  userId: user.id,
  userName: user.name,
}), [user.id, user.name]);

<InAppAI context={context} />

Keep context lightweight:

// Good - lightweight
context={{
  userId: user.id,
  page: 'dashboard',
}}

// Avoid - too much data
context={{
  user: fullUserObject,
  allProducts: productCatalog,
}}

Browser Compatibility

InAppAI React supports:

  • Chrome 80+
  • Firefox 75+
  • Safari 13+
  • Edge 80+

Need Help?