Overview
The Suada Vanilla JavaScript SDK provides a framework-agnostic way to integrate Suada’s AI capabilities into any web application. Built with modern JavaScript practices, it offers a lightweight, zero-dependency solution that works seamlessly in any browser environment.
Prerequisites
- Modern browsers (Chrome 60+, Firefox 60+, Safari 12+, Edge 79+)
- Node.js 16.0.0 or higher (for npm installation)
- A Suada API key
- Basic understanding of JavaScript and DOM manipulation
Installation
Choose the installation method that best suits your project:
NPM Installation
# Using npm
npm install @suada/vanilla @suada/core
# Using yarn
yarn add @suada/vanilla @suada/core
CDN Installation
Add the following script tag to your HTML:
<script src="https://cdn.jsdelivr.net/npm/@suada/vanilla/dist/suada.min.js"></script>
Quick Start
Here’s a basic example to get you started:
<!DOCTYPE html>
<html>
<head>
<title>Suada Chat Example</title>
</head>
<body>
<div id="chat-container"></div>
<script src="https://cdn.jsdelivr.net/npm/@suada/vanilla/dist/suada.min.js"></script>
<script>
// Initialize Suada client
const suada = new Suada.Client({
apiKey: 'your-api-key'
});
// Create a chat instance
const chat = new Suada.Chat({
container: '#chat-container',
onMessageSubmit: (message) => console.log('Message sent:', message),
onResponseReceived: (response) => console.log('Response:', response)
});
// Initialize the chat
chat.initialize();
</script>
</body>
</html>
Authentication
Setting up your API Key
For development, you can use your API key directly:
const client = new Suada.Client({
apiKey: 'your-api-key'
});
For production, we recommend using environment variables:
// Using webpack or similar bundler
import { config } from './config';
const client = new Suada.Client({
apiKey: config.apiKey,
environment: 'production'
});
Configuration Options
Option | Type | Required | Description |
---|
apiKey | string | Yes | Your Suada API key |
environment | ’development’ | ‘production’ | No | Environment setting (defaults to ‘development’) |
baseUrl | string | No | Custom API base URL |
debug | boolean | No | Enable debug logging |
timeout | number | No | Request timeout in milliseconds |
Core Components
Chat Component
A pre-built chat interface:
const chat = new Suada.Chat({
container: '#chat-container',
theme: 'light',
placeholder: 'Ask a question...',
initialMessages: [],
privacyMode: true,
onMessageSubmit: (message) => {
console.log('Message:', message);
},
onResponseReceived: (response) => {
console.log('Response:', response);
}
});
Options
Option | Type | Required | Description |
---|
container | string | HTMLElement | Yes | Target container element or selector |
theme | ’light’ | ‘dark’ | No | UI theme (defaults to ‘light’) |
placeholder | string | No | Input placeholder text |
initialMessages | Message[] | No | Pre-loaded chat messages |
privacyMode | boolean | No | Enable enhanced privacy features |
Integration Components
Create OAuth integration buttons:
const button = new Suada.IntegrationButton({
container: '#integration-button',
provider: 'notion',
redirectUri: 'https://your-app.com/callback',
onSuccess: (result) => console.log('Connected:', result),
onError: (error) => console.error('Error:', error)
});
Client API
Chat Methods
Send and receive messages:
// Send a message
const response = await client.sendMessage({
message: "What's the latest update?",
privacyMode: true
});
// Get chat history
const history = await client.getChatHistory();
// Clear chat history
await client.clearChatHistory();
Integration Methods
Manage integrations programmatically:
// Initialize OAuth flow
const authUrl = await client.initializeOAuth('notion', {
redirectUri: 'https://your-app.com/callback'
});
// Handle OAuth callback
const result = await client.handleOAuthCallback({
provider: 'notion',
code: urlParams.get('code'),
state: urlParams.get('state')
});
// List integrations
const integrations = await client.getIntegrations();
Error Handling
The SDK provides comprehensive error handling:
try {
await client.sendMessage({ message: "Hello" });
} catch (error) {
if (error instanceof Suada.APIError) {
// Handle API-specific errors
console.error('API Error:', error.message, error.status);
} else if (error instanceof Suada.NetworkError) {
// Handle network-related errors
console.error('Network Error:', error.message);
} else {
// Handle unexpected errors
console.error('Unexpected error:', error);
}
}
Styling
Using CSS Variables
Customize the appearance using CSS variables:
:root {
--suada-primary-color: #007bff;
--suada-background-color: #ffffff;
--suada-text-color: #333333;
--suada-border-radius: 8px;
--suada-font-family: system-ui, -apple-system, sans-serif;
}
Custom CSS Classes
Override default styles with custom classes:
const chat = new Suada.Chat({
container: '#chat-container',
className: 'custom-chat',
messageClassName: 'custom-message',
inputClassName: 'custom-input'
});
Best Practices
Security
- Store API keys securely
- Implement proper CORS settings
- Use privacy mode for sensitive data
- Secure OAuth callback endpoints
- Clean up components when not in use
- Implement proper error handling
- Use debouncing for user input
- Optimize network requests
Development
- Follow JavaScript best practices
- Implement proper error boundaries
- Use TypeScript for better type safety
- Keep dependencies updated
FAQ
How do I handle CORS issues?
Configure your server to allow requests from your domain:
const client = new Suada.Client({
apiKey: 'your-api-key',
baseUrl: 'https://api.suada.ai',
headers: {
'Origin': window.location.origin
}
});
How do I implement retry logic?
Configure retry behavior in the client:
const client = new Suada.Client({
apiKey: 'your-api-key',
maxRetries: 3,
retryDelay: 1000,
retryCondition: (error) => error.status === 429
});
How do I handle rate limiting?
Implement exponential backoff:
const client = new Suada.Client({
apiKey: 'your-api-key',
rateLimitConfig: {
maxRetries: 3,
initialDelay: 1000,
maxDelay: 10000,
backoffFactor: 2
}
});
How can I debug the SDK?
Enable debug mode and use the logger:
const client = new Suada.Client({
apiKey: 'your-api-key',
debug: true,
logger: (message) => console.log('[Suada]', message)
});
How do I implement custom authentication?
Use the auth provider option:
const client = new Suada.Client({
apiKey: 'your-api-key',
authProvider: async () => {
const token = await getCustomToken();
return { Authorization: `Bearer ${token}` };
}
});
Support & Resources
Documentation
Support