A production-ready AI chatbot widget for SvelteKit with Server-Sent Events (SSE) streaming. Built with Svelte 5 runes.
- 🚀 Svelte 5 Runes - Modern reactive state management
- 💬 Real-time Streaming - SSE support for responsive AI interactions
- 🎨 Fully Customizable - Themes, slots, and CSS custom properties
- 🌍 i18n Ready - All UI text exposed through props
- ⌨️ Keyboard Navigation - Escape to close, Enter to send
- 📱 Responsive Design - Works on mobile and desktop
- 🔒 Session Persistence - Resume conversations automatically
- 🪶 Lightweight - Under 50KB gzipped
npm install @studiozandra/svelte-ai-chat-widgetThe easiest way to get started is with the interactive setup:
npx svelte-ai-chat-widget setupThis will:
- ✅ Install backend API endpoints (chat send & history)
- ✅ Install database utilities (SQLite)
- ✅ Install environment config & rate limiting
- ✅ Create a demo page (optional)
- ✅ Show you next steps
# Install required dependencies
npm install @anthropic-ai/sdk better-sqlite3 @types/better-sqlite3 better-auth
# Set up your API key
cp .env.example .env
# Add your ANTHROPIC_API_KEY to .envnpm run devVisit the demo page (default: http://localhost:5173/chatbot-demo) to see it in action!
If you prefer manual setup:
<script lang="ts">
import { ChatWidget } from '@studiozandra/svelte-ai-chat-widget';
</script>
<ChatWidget
sendMessageEndpoint="/api/chat/send"
historyEndpoint="/api/chat/history"
theme="light"
/>Then copy backend files from templates/backend/ to your project.
| Prop | Type | Required | Description |
|---|---|---|---|
sendMessageEndpoint |
string |
Yes | POST endpoint for sending messages (SSE stream) |
historyEndpoint |
string |
Yes | GET endpoint for conversation history |
context |
Record<string, any> |
No | Additional context sent with each request |
theme |
'light' | 'dark' | string |
No | Built-in theme or custom CSS class |
i18n |
object |
No | Customize UI text |
{
placeholder?: string; // Default: "Type your message..."
title?: string; // Default: "Chat"
sendButton?: string; // Default: "Send"
errorMessage?: string; // Default: "Something went wrong"
}<ChatWidget
{...props}
onopen={() => console.log('Chat opened')}
onclose={() => console.log('Chat closed')}
onmessage={(msg) => console.log('Message:', msg)}
/><ChatWidget theme="light" {...props} />
<ChatWidget theme="dark" {...props} />:root {
--chat-bubble-bg: #4f46e5;
--chat-bubble-color: white;
--chat-window-bg: white;
--chat-header-bg: #4f46e5;
--chat-header-color: white;
--chat-user-message-bg: #4f46e5;
--chat-user-message-color: white;
--chat-assistant-message-bg: #f3f4f6;
--chat-input-border: #e5e7eb;
--chat-send-button-bg: #4f46e5;
}<ChatWidget {...props}>
{#snippet header()}
<div class="custom-header">
<img src="/logo.png" alt="Logo" />
<h3>Support Chat</h3>
</div>
{/snippet}
</ChatWidget><ChatWidget {...props}>
{#snippet footer()}
<p>Your conversations are private and encrypted.</p>
{/snippet}
</ChatWidget>The widget requires two endpoints:
Request:
{
"message": "Hello, AI!",
"sessionId": "optional-uuid",
"context": { "userId": "123" }
}Response: Server-Sent Events stream
data: {"chunk": "Hello"}
data: {"chunk": " there!"}
data: {"done": true, "sessionId": "uuid"}
Request:
GET /api/chat/history?sessionId=uuid&limit=50&offset=0
Response:
{
"messages": [
{
"id": "msg-1",
"role": "user",
"content": "Hello!",
"timestamp": 1234567890000
}
],
"hasMore": false
}📖 Complete Backend Implementation Guide →
Full TypeScript support with exported types:
import type {
ChatWidgetProps,
Message,
ChatSession,
HistoryResponse,
SendMessageRequest
} from '@studiozandra/svelte-ai-chat-widget';import { createChatStore } from '@studiozandra/svelte-ai-chat-widget';
const chatStore = createChatStore();
// Access state
console.log(chatStore.messages);
console.log(chatStore.isOpen);
// Control widget
chatStore.open();
chatStore.close();
chatStore.addMessage({ role: 'user', content: 'Hello' });- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
The included backend implementation provides:
- ✅ API key security (server-side only)
- ✅ User authentication (Better Auth required)
- ✅ Session validation (user-scoped chat history)
- ✅ Rate limiting (10 req/min default)
- ✅ Input validation
- ✅ SQL injection prevention
Authentication Requirements:
- 🔒 Better Auth must be configured
- 🔒 All chat endpoints require authenticated sessions
- 🔒 Users can only access their own chat history
- 🔒 User IDs are server-verified (not client-provided)
Production recommendations:
- Use HTTPS
- Enable CORS properly
- Add content moderation
- Set up proper session management
MIT © studiozandra