subtitle

Blog

subtitle

How to
Make an AI Chatbot in JavaScript

JavaScript is perfect for creating chatbots on websites or
web apps because it runs directly in browsers

How to Make an AI Chatbot in JavaScript

JavaScript is perfect for creating chatbots on websites or web apps because it runs directly in browsers and integrates easily with APIs.

1. Decide the Type of Chatbot

  1. Rule-Based Chatbot

    • Uses predefined responses based on keywords.

    • Simple and works offline.

    • Example: basic greeting or FAQ bot.

  2. AI-Powered Chatbot

    • Uses AI models (like OpenAI GPT) for dynamic, natural conversations.

    • Can understand context, answer complex queries, and provide personalised responses.

2. Build a Simple Rule-Based Chatbot (JavaScript)

This chatbot runs directly in the browser.

<!DOCTYPE html>
<html>
<head>
<title>Simple Chatbot</title>
<style>

#chatbox { width: 300px; height: 400px; border: 1px solid #ccc; overflow-y:
scroll; padding: 10px; }
#userInput { width: 240px; }
</style>
</head
<body>
<div id=“chatbox”></div>

<input type=“text” id=“userInput”

placeholder="Type your message">
<button onclick="sendMessage()">Send</button><script>
const chatbox = document.getElementById(“chatbox”);
function botResponse(message) {
message = message.toLowerCase();
if (message.includes("hello") || message.includes("hi")) return "Hello! How can
I
help you today?";
if (message.includes("bye")) return "Goodbye! Have a nice day!";
return "Sorry, I didn't understand that.";

}function

sendMessage() {
const userInput = document.getElementById("userInput").value;
chatbox.innerHTML += "<b>You:</b> " + userInput + "<br>";
const
response = botResponse(userInput);
chatbox.innerHTML += "<b>Bot:</b> " + response + "<br>";
document.getElementById("userInput").value = "";
chatbox.scrollTop = chatbox.scrollHeight;
}
</script></body>
</html>

Features:

  • Simple keyword matching.

  • Works fully in the browser without servers.

3. Build an AI-Powered Chatbot Using OpenAI GPT

To use GPT for your JavaScript chatbot, you’ll need an OpenAI API key.

Step 1: Get OpenAI API Key

  • Sign up at OpenAI

  • Generate an API key.

Step 2: Create a Node.js Backend

Install dependencies:

npm init -y
npm install express body-parser node-fetch dotenv

server.js

import express from "express";
import fetch from "node-fetch";
import bodyParser from "body-parser";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(bodyParser.json());app.post(“/chat”, async (req, res) => {
const userMessage = req.body.message;

 

const response =

await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization":
`Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a helpful
chatbot." },
{ role: "user", content: userMessage }
]
})
});const data = await response.json();
res.json({ reply:
data.choices[0].message.content
});

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

 

  • Uses Express.js to handle chat requests.

  • Sends user input to the OpenAI GPT API.

  • Returns AI response to the client.

Step 3: Connect Frontend to Backend

index.html

<div id="chatbox"></div>
<input type="text" id="userInput" placeholder="Type a message">

<button onclick="sendMessage()">Send</button><script>

async function sendMessage() {
const userInput = document.getElementById("userInput").value;
document.getElementById("chatbox").innerHTML += "

<b>You:</b> " + userInput + "<br>";

 

const response = await fetch(“http://localhost:3000/chat”, {

 

method: “POST”,

 

headers: { “Content-Type”:

"application/json" },
body: JSON.stringify({ message: userInput })

});const data = await response.json();

document.getElementById("chatbox").innerHTML += "<b>Bot:</b> " + data.reply + "<br>";
document.getElementById("userInput").value = "";
}
</script>
  • Sends the user message to the Node.js server.

  • Receives AI response and displays it in chatbox.

4. Add Context for Multi-Turn Conversations

Store conversation history in the server:

let conversationHistory = [
{ role: "system", content: "You are a helpful AI chatbot." }
];
app.post(“/chat”, async (req, res) => {
const
userMessage = req.body.message;

conversationHistory.push({ role: "user", content: userMessage });

 

const response = await

fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer
${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: conversationHistory
})

});const data = await

response.json();
const botReply = data.choices[0].message.content;

conversationHistory.push({ role: "assistant", content: botReply });

 

res.json({

reply: botReply });
});
  • Maintains context for more natural conversations.

5. Optional: Add Knowledge Base

You can add domain-specific answers by checking keywords before calling GPT:

const knowledgeBase = {
shipping: "Our shipping takes 3-5 business days.",
returns: "You can return products within 30 days."

};const botReply =

knowledgeBase[userMessage.toLowerCase()] || aiReply;
  • Combines static knowledge with AI responses.

6. Deploy Your JavaScript Chatbot

  • Web Hosting: Vercel, Netlify, or GitHub Pages for the frontend.

  • Backend Hosting: Heroku, Render, or AWS for Node.js server.

  • Messaging Apps: Integrate with Telegram, WhatsApp, or Slack using APIs.

7. Tips for a Better Chatbot

  1. Use multi-turn context for natural conversations.

  2. Limit user input length to prevent errors.

  3. Add fallback responses for unknown queries.

  4. Test across browsers and devices.

  5. Track chat logs to improve responses.

Conclusion

You can create a rule-based AI chatbot quickly in JavaScript for websites or an AI-powered chatbot using OpenAI GPT for dynamic conversations. By combining frontend HTML/JS with a backend server, you can handle natural language input, maintain conversation context, and integrate domain knowledge.