Skip to content

studiozandra/svelte-AIchat-widget

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

@studiozandra/svelte-ai-chat-widget

A production-ready AI chatbot widget for SvelteKit with Server-Sent Events (SSE) streaming. Built with Svelte 5 runes.

npm version License: MIT

Features

  • πŸš€ 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

Installation

npm install @studiozandra/svelte-ai-chat-widget

Quick Start

1. Run Setup CLI

The easiest way to get started is with the interactive setup:

npx svelte-ai-chat-widget setup

This 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

2. Configure Environment

# 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 .env

3. Start Development Server

npm run dev

Visit the demo page (default: http://localhost:5173/chatbot-demo) to see it in action!


Manual Setup (Alternative)

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.

πŸ“– Full Backend Setup Guide β†’

Props

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

i18n Options

{
  placeholder?: string;      // Default: "Type your message..."
  title?: string;           // Default: "Chat"
  sendButton?: string;      // Default: "Send"
  errorMessage?: string;    // Default: "Something went wrong"
}

Events

<ChatWidget
  {...props}
  onopen={() => console.log('Chat opened')}
  onclose={() => console.log('Chat closed')}
  onmessage={(msg) => console.log('Message:', msg)}
/>

Theming

Built-in Themes

<ChatWidget theme="light" {...props} />
<ChatWidget theme="dark" {...props} />

Custom CSS Variables

: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;
}

Slots

Custom Header

<ChatWidget {...props}>
  {#snippet header()}
    <div class="custom-header">
      <img src="/logo.png" alt="Logo" />
      <h3>Support Chat</h3>
    </div>
  {/snippet}
</ChatWidget>

Custom Footer

<ChatWidget {...props}>
  {#snippet footer()}
    <p>Your conversations are private and encrypted.</p>
  {/snippet}
</ChatWidget>

Backend API Specification

The widget requires two endpoints:

POST /api/chat/send

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"}

GET /api/chat/history

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 β†’

TypeScript Support

Full TypeScript support with exported types:

import type {
  ChatWidgetProps,
  Message,
  ChatSession,
  HistoryResponse,
  SendMessageRequest
} from '@studiozandra/svelte-ai-chat-widget';

Advanced Usage

Programmatic Control

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' });

Browser Support

  • Chrome/Edge 90+
  • Firefox 88+
  • Safari 14+

Security

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

License

MIT Β© studiozandra

Links

About

an npm package with a chatbot widget template and simple backend for AI API calls

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors