Skip to main content

How to Add AI Chatbot to Website with JavaScript in 2026

All articles
Tutorial

How to Add AI Chatbot to Website with JavaScript in 2026

Technical guide to embedding AI assistants on any website. Covers JavaScript widget, React integration, iframe, and REST API with code examples.

How to Add AI Chatbot to Website with JavaScript in 2026
Table of Contents

Why Embed an AI Assistant on Your Website?

AI assistants can dramatically improve user engagement by providing instant answers, reducing bounce rates, and automating customer support. Whether you're building a documentation site, e-commerce platform, or SaaS dashboard, embedding an AI assistant gives visitors a modern, conversational interface without requiring them to leave your site.

From a technical standpoint, embedding an AI assistant is simpler than it seems. You have multiple integration options:

  • JavaScript Widget: Lightweight, customizable, and runs in the DOM.
  • React Component: Built specifically for React apps with hooks and state management.
  • iframe Embed: Cross-domain friendly, works with any backend.
  • REST API: Full control over requests and responses.

Let’s walk through each approach with code examples and best practices.


Option 1: JavaScript Widget Integration

JavaScript widgets are ideal for static sites, WordPress, or any HTML-based platform.

Step 1: Include the SDK

Add the following script to your HTML <head> or before the closing </body> tag:

html
<script src="https://your-ai-service.com/sdk/assistant.js" defer></script>

Replace https://your-ai-service.com with your AI provider’s endpoint (e.g., https://api.yourcompany.com/ai).

Step 2: Initialize the Widget

Create a container element where the widget will appear:

html
<div id="ai-assistant-widget"></div>

Then initialize the widget using JavaScript:

javascript
document.addEventListener('DOMContentLoaded', function() {
  const widget = window.AIAssistant.init({
    container: '#ai-assistant-widget',
    theme: 'light',
    position: 'bottom-right',
    welcomeMessage: 'Hello! How can I help you today?',
    apiEndpoint: 'https://api.yourcompany.com/ai/chat',
    apiKey: 'your-api-key-here'
  });

  // Optional: Track events
  widget.on('messageSent', (data) => {
    console.log('Message sent:', data.message);
  });
});

Key Configuration Options

OptionTypeDescription
containerstringCSS selector for the widget container
themestringlight or dark
positionstringtop-left, top-right, bottom-left, bottom-right
welcomeMessagestringInitial greeting text
apiEndpointstringURL to your AI endpoint
apiKeystringAuthentication key

Security Tip: Never expose API keys in client-side code in production. Use a backend proxy to fetch responses and inject the API key server-side.

Styling the Widget

You can override default styles via CSS:

css
#ai-assistant-container {
  font-family: 'Inter', sans-serif;
}

#ai-assistant-header {
  background-color: #0052ff;
  color: white;
}

Option 2: React Integration (Recommended for SPAs)

If your site uses React (Next.js, Gatsby, etc.), a dedicated React component offers better state synchronization and performance.

Step 1: Install the Package

bash
npm install @yourcompany/ai-assistant-react
# or
yarn add @yourcompany/ai-assistant-react

Step 2: Use the Component

jsx
import React from 'react';
import AIAssistant from '@yourcompany/ai-assistant-react';

export default function App() {
  return (
    <div className="app">
      <h1>Welcome</h1>
      <AIAssistant
        theme="dark"
        position="bottom-right"
        welcomeMessage="Ask me anything!"
        apiEndpoint={process.env.NEXT_PUBLIC_AI_ENDPOINT}
        apiKey={process.env.NEXT_PUBLIC_AI_API_KEY}
      />
    </div>
  );
}

Using Custom Hooks for Advanced Control

For apps needing full control over chat state:

jsx
import { useAIAssistant } from '@yourcompany/ai-assistant-react';

function ChatWidget() {
  const {
    messages,
    input,
    isLoading,
    sendMessage,
    setInput
  } = useAIAssistant({
    apiEndpoint: '/api/ai/chat',
    initialMessages: [{ role: 'assistant', content: 'Hello!' }]
  });

  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((msg, i) => (
          <div key={i} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      <input
        value={input} => setInput(e.target.value)} => e.key === 'Enter' && sendMessage()}
        disabled={isLoading}
      />
    </div>
  );
}

Pro Tip: Use environment variables (NEXT_PUBLIC_*) for API endpoints in frameworks like Next.js to avoid hardcoding secrets.


Option 3: iframe Embed (Zero-Code Solution)

Perfect for non-technical users or rapid deployment.

Step 1: Generate iframe Code

Most AI platforms provide an “Embed” section. Example:

html
<iframe
  src="https://chat.yourcompany.com/embed?apiKey=user123&theme=dark"
  width="400"
  height="500"
  frameborder="0"
  style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);"
></iframe>

Step 2: Customize Dimensions and Appearance

  • Use width and height to control size.
  • Add style for rounded corners, shadows, and responsiveness.

Step 3: Handle Cross-Origin Communication (Optional)

Use postMessage to communicate between parent and iframe:

javascript
// In parent page
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(
  { type: 'SET_THEME', payload: 'dark' },
  'https://chat.yourcompany.com'
);

// In iframe (inside chat app)
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://your-parent-site.com') return;
  if (event.data.type === 'SET_THEME') {
    document.body.className = event.data.payload;
  }
});

⚠️ Always validate event.origin to prevent XSS attacks.


Option 4: REST API Integration (Full Control)

For developers who want full control over UI and logic.

Step 1: Set Up a Chat API Endpoint

javascript
// Example using Express.js
const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/api/ai/chat', async (req, res) => {
  try {
    const response = await axios.post(
      'https://api.openai.com/v1/chat/completions',
      {
        model: 'gpt-4',
        messages: req.body.messages
      },
      {
        headers: {
          'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
    res.json(response.data.choices[0].message);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

Step 2: Build a Simple Chat UI

jsx
import React, { useState } from 'react';

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  const sendMessage = async () => {
    if (!input.trim()) return;

    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');

    const response = await fetch('/api/ai/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: [...messages, userMessage] })
    });

    const data = await response.json();
    setMessages(prev => [...prev, data]);
  };

  return (
    <div>
      <div className="messages">
        {messages.map((m, i) => (
          <div key={i}>{m.role === 'user' ? 'You: ' : 'AI: '}{m.content}</div>
        ))}
      </div>
      <input
        value={input} => setInput(e.target.value)} => e.key === 'Enter' && sendMessage()}
      />
    </div>
  );
}

Advantages of REST API Integration

  • Full UI customization
  • Offline mode with local caching
  • Analytics and logging
  • Integration with existing state management (Redux, Zustand, etc.)

Best Practices for All Methods

1. Performance Optimization

  • Lazy-load the AI widget only when a user clicks a chat button.
  • Use IntersectionObserver to load assets when the chat icon is visible.
  • Minify and compress SDK and assets.

2. Security

  • Never expose API keys in client-side code.
  • Use backend middleware to proxy AI requests.
  • Sanitize user input to prevent prompt injection.
javascript
// Example: Sanitize user input
function sanitizeInput(text) {
  return text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

3. Accessibility

  • Ensure contrast ratios meet WCAG standards.
  • Use ARIA roles: role="dialog", aria-label="AI Assistant".
  • Support keyboard navigation (Tab, Enter, Escape).

4. Analytics and Monitoring

Track key events:

javascript
widget.on('messageSent', (data) => {
  analytics.track('AI Message Sent', {
    userId: user.id,
    message: data.message,
    timestamp: new Date().toISOString()
  });
});

5. Fallback Content

Provide a fallback for users who disable JavaScript:

html
<noscript>
  <div className="ai-fallback">
    <p>AI Assistant is not available without JavaScript.</p>
    <button>Contact Support</button>
  </div>
</noscript>

Choosing the Right Method

MethodBest ForDifficultyCustomizationSecurity
JavaScript WidgetSimple sites, blogsLowMediumMedium
React ComponentSPAs, Next.js, GatsbyMediumHighMedium
iframe EmbedWordPress, CMS, quick setupVery LowLowHigh
REST APIFull control, complex appsHighVery HighHigh

Final Thoughts

Embedding an AI assistant doesn’t have to be complex. Start with a JavaScript widget or iframe for rapid deployment, then migrate to a React component or REST API as your needs grow. Focus on security, performance, and user experience—your visitors will thank you with longer engagement and higher satisfaction.

Whether you're launching a new feature or upgrading support, AI assistants are now accessible to every website. Pick the integration path that fits your stack, and start conversing with your users today.

foundationalbusinessdevelopersintegrationtutorialquality_flagged
Enjoyed this article? Share it with others.

More to Read

View all posts
Tutorial

How to Build an AI Assistant in 10 Minutes Without Coding (2026)

Building your own AI assistant used to require a developer. With Assisters, anyone can create, train, and deploy a powerful AI assister in under 10 minutes — no code needed.

6 min read
Tutorial

How to Build an AI Assistant in 30 Minutes (No Coding) 2026

A quick-start guide for creators who want to monetize their knowledge with AI. Go from idea to published assistant in half an hour.

9 min read
Tutorial

Best File Types to Train AI Assistants in 2026: Expert Guide

A comprehensive guide to file formats, best practices, and optimization tips for training your AI assistant&apos;s knowledge base.

16 min read
Tutorial

How to Build an AI Chatbot in 2026: No-Code Tools Compared

Step-by-step guide to creating your own AI chatbot without writing any code. No technical skills required.

7 min read

Build with the Assisters API

Integrate specialized AI assistants into your apps with our simple REST API. Get your API key in seconds.

Earn 20% recurring commission

Share Assisters with friends and earn from their subscriptions.

Start Referring