0.1.2 • Published 1 year ago

@otto-ai/react v0.1.2

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Otto React

npm version TypeScript License: MIT

A powerful React integration for the Otto chat widget, featuring first-class support for Next.js and modern React applications.

Features

  • 🚀 First-class Next.js App Router support
  • 💪 Full TypeScript support
  • 🔒 Secure authentication handling
  • 🎨 Customizable UI and theming
  • 🔌 Framework-agnostic core
  • 📱 Responsive design

Installation

npm install @otto-ai/react
# or
yarn add @otto-ai/react
# or
pnpm add @otto-ai/react

Quick Start

  1. Add your Otto credentials to .env.local:
OTTO_HMAC_SECRET=your_secret_from_otto_dashboard
OTTO_MAILBOX_SLUG=your_mailbox_slug
  1. Use in your application (Next.js example):
// app/layout.tsx
import { OttoProvider, generateOttoAuth } from '@otto-ai/react';

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await auth(); // Your auth solution
  if (!session?.user?.email) return children;

  const ottoAuth = await generateOttoAuth({
    email: session.user.email
  });
  
  const config = {
    ...ottoAuth,
    title: 'Support',
  };

  return (
    <html>
      <body>
        <OttoProvider {...config}>
          {children}
        </OttoProvider>
      </body>
    </html>
  );
}

For other frameworks, ensure authentication is always generated server-side:

// pages/api/otto-auth.ts
import { generateOttoAuth } from '@otto-ai/react/server';

export default async function handler(req, res) {
  const session = await getSession(req); // Your auth solution
  if (!session?.user?.email) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const ottoAuth = await generateOttoAuth({
    email: session.user.email
  });

  res.json(ottoAuth);
}

Anonymous Sessions

Otto also supports anonymous sessions that don't require user authentication. Here's how to implement them:

// app/public-chat.tsx
import { OttoProvider } from '@otto-ai/react';

export default async function PublicChat() {
  const config = {
    mailbox_slug: process.env.OTTO_MAILBOX_SLUG,
    title: 'Public Support Chat'
  };

  return (
    <div>
      <h1>Public Support Chat</h1>
      <OttoProvider {...config}>
        <ChatContent />
      </OttoProvider>
    </div>
  );
}

For API routes:

// pages/api/public-otto-auth.ts
export default async function handler(req, res) {
  res.json({
    mailbox_slug: process.env.OTTO_MAILBOX_SLUG
  });
}

Configuration

Session Types

Otto supports two types of sessions:

Authenticated Sessions

Require user email and generate secure HMAC authentication:

const config = await generateOttoAuth({
  email: user.email,
  // Optional: provide HMAC secret directly instead of using env var
  hmacSecret: 'your_secret',
  // Optional: provide mailbox slug directly instead of using env var
  mailboxSlug: 'your_mailbox'
});

Anonymous Sessions

Only require a mailbox slug, no authentication needed:

const config = {
  mailbox_slug: 'your_mailbox',
  title: 'Support Chat' // optional
};

Note: Anonymous sessions have limited functionality:

  • No conversation history
  • No user-specific features
  • Messages are not associated with an email address

Customer Metadata Examples

Below are common patterns for different use cases:

// SaaS Application
const metadata = {
  name: user.displayName,
  value: user.lifetimeValue, // Total value from all subscriptions
  links: {
    'User Profile': `/users/${user.id}`,
    'Billing History': `/users/${user.id}/billing`,
    'Support Tickets': `/users/${user.id}/tickets`
  }
};

// E-commerce Platform
const metadata = {
  name: customer.name,
  value: customer.totalSpent, // Total spent across all orders
  links: {
    'Customer Profile': `/customers/${customer.id}`,
    'Order History': `/customers/${customer.id}/orders`,
    'Return Requests': `/customers/${customer.id}/returns`
  }
};

Best Practices

Security

  • Keep OTTO_HMAC_SECRET secure and never expose it client-side
  • Generate authentication tokens server-side
  • Validate user sessions before initializing Otto
  • Use environment variables for sensitive configuration

Performance

  • Initialize Otto only after user authentication
  • Implement proper cache invalidation strategies
  • Use framework-specific optimizations when available

API Reference

Hooks

useOtto()

const { 
  show,           // () => void
  hide,           // () => void
  toggle,         // () => void
  sendPrompt,     // (prompt: string) => void
  isVisible       // boolean
} = useOtto();

Components

OttoProvider

<OttoProvider
  {...authConfig}
>
  {children}
</OttoProvider>

Troubleshooting

Common Issues

Widget Not Loading

  • Verify environment variables are correctly set
  • Ensure HMAC generation is working
  • Check network requests for authentication errors

Authentication Failures

  • Confirm HMAC secret matches dashboard
  • Verify timestamp is current
  • Validate email format and consistency

License

MIT © Otto

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago