Build a free AI chatbot with Node.js and a plain web page, using Gemini’s free tier: streaming replies, conversation memory, and a system prompt. Ollama and Claude options included.

By Michael Stromberg, Hack Reactor graduate (2016) · Last verified November 29, 2026
In this tutorial you’ll build a working AI chatbot in JavaScript, for free: a small Node.js server that talks to a large language model (LLM), and a web page where you chat with it. Replies stream in word by word, the bot remembers the conversation, and your API key stays safely on the server. It takes about 100 lines of code and no frameworks.
The short answer: an AI chatbot is a loop. Your page sends the user’s message to your server; your server sends the whole conversation so far, plus a “system prompt” describing how the bot should behave, to an LLM; the reply streams back to the page; and the server saves it so the next message includes it. We’ll use Google’s Gemini API, which has a free tier that needs no credit card. You’ll also see how to swap in a model that runs free and offline on your own computer with Ollama, or a paid model such as Anthropic’s Claude, by changing one block of code.
What you’ll build
A “Study Buddy” chatbot that answers coding questions in plain language. It has three parts:
- The page (
index.html): a chat window that sends your message and shows the reply as it arrives. - The server (
server.js): keeps each conversation’s history, calls the AI, and streams the reply back. It’s also the only place your secret API key lives. - The AI model: Google’s Gemini, through its free tier. One clearly marked block of the server is the only code that knows which AI you’re using.

Before you start
- Node.js 22 or later. Check with
node --versionin a terminal. Google’s JavaScript library requires version 22. - A free Gemini API key. Sign in to Google AI Studio at
aistudio.google.comwith a Google account and create an API key. The free tier needs no credit card. It has limits on requests per minute and per day, which vary by model and are shown in AI Studio; a tutorial chatbot stays well within them. - Basic JavaScript: functions,
async/await, and objects. If those feel shaky, our coding bootcamp prep guide has practice problems.
Two things to know about free API keys. First, Google’s terms allow it to use what you send on the free tier to improve its products, so don’t paste anything private into your chatbot. Second, never put an API key in browser code: anyone can read a web page’s JavaScript, and a leaked key lets strangers use up your quota (or, on a paid plan, your money). That’s why this chatbot has a server: the browser talks to your server, and only your server talks to the AI.
Step 1: Set up the project
Create a folder, add a package.json, and install Google’s official Gemini library:
mkdir study-buddy cd study-buddy npm init -y npm pkg set type=module npm install @google/genai
type=module lets you use modern import statements. Then give the server your API key as an environment variable, so it never appears in your code:
# macOS or Linux export GEMINI_API_KEY="your-key-here" # Windows PowerShell $env:GEMINI_API_KEY="your-key-here"
The library reads GEMINI_API_KEY automatically. If you use Git, never commit a key to your repository; our Git and GitHub guide covers the basics.
Step 2: Write the server
Create server.js with this code. Apart from the Gemini library, it uses only what’s built into Node:
import http from "node:http";
import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
const SYSTEM_PROMPT =
"You are Study Buddy, a friendly tutor for people learning to code. " +
"Explain ideas in plain language, use short JavaScript examples, " +
"and keep answers under 150 words unless the student asks for more.";
// --- AI provider: swap this block to use a different AI ---
import { GoogleGenAI } from "@google/genai";
// Reads your free API key from the GEMINI_API_KEY environment variable.
const ai = new GoogleGenAI({});
const MODEL = "gemini-3.5-flash-lite";
// Sends the conversation to the AI, calls onText with each piece of the reply
// as it arrives, and returns the full reply.
async function streamReply(history, onText) {
const stream = await ai.models.generateContentStream({
model: MODEL,
// Gemini calls the assistant "model" and wraps text in "parts".
contents: history.map((m) => ({
role: m.role === "assistant" ? "model" : "user",
parts: [{ text: m.content }],
})),
config: { systemInstruction: SYSTEM_PROMPT },
});
let reply = "";
for await (const chunk of stream) {
const text = chunk.text ?? "";
reply += text;
onText(text);
}
return reply;
}
// --- end of AI provider ---
// Each conversation's history, kept on the server and keyed by an ID.
const conversations = new Map();
async function readJson(req) {
let body = "";
for await (const chunk of req) body += chunk;
return JSON.parse(body || "{}");
}
async function handleChat(req, res) {
let body;
try {
body = await readJson(req);
} catch {
res.writeHead(400).end("Invalid JSON");
return;
}
const text = typeof body.message === "string" ? body.message.trim() : "";
if (!text) {
res.writeHead(400).end("Message is required");
return;
}
// Continue an existing conversation, or start a new one.
const id = conversations.has(body.conversationId) ? body.conversationId : randomUUID();
const history = conversations.get(id) ?? [];
history.push({ role: "user", content: text });
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8",
"X-Conversation-Id": id,
});
try {
// Send each piece of the reply to the browser as soon as it arrives.
const reply = await streamReply(history, (piece) => res.write(piece));
if (reply) {
history.push({ role: "assistant", content: reply }); // remember it for next time
} else {
history.pop(); // no answer came back, so forget the question
res.write("(No reply came back. Try rephrasing your question.)");
}
conversations.set(id, history);
} catch (error) {
history.pop(); // the question never got an answer, so drop it
console.error(error);
const status = error.status ?? error.status_code;
res.write(
status
? `\n\n(The AI service returned an error ${status}. Please try again.)`
: "\n\n(Something went wrong. Please try again.)",
);
}
res.end();
}
const server = http.createServer(async (req, res) => {
if (req.method === "GET" && req.url === "/") {
const html = await readFile(new URL("./index.html", import.meta.url));
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(html);
} else if (req.method === "POST" && req.url === "/api/chat") {
await handleChat(req, res);
} else {
res.writeHead(404).end("Not found");
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Study Buddy is running at http://localhost:${PORT}`));How the server works
- The system prompt (
SYSTEM_PROMPT) tells the model who it is and how to answer. Change it and you change the bot’s personality, tone, and rules. - The AI-provider block holds everything specific to Gemini: the import, the model name, and
streamReply(). The rest of the server only callsstreamReply(history, onText), which is why you can swap AIs later by replacing this one block. - Conversation history. The AI doesn’t remember anything between requests. To make the bot remember, the server keeps each conversation’s messages in a
Mapand sends all of them every time. Gemini calls the bot’s side of the conversation"model"and wraps text inparts, sostreamReply()converts each message into that shape. - Streaming.
generateContentStream()returns the reply in pieces. Thefor awaitloop passes each piece toonText, which writes it straight to the browser, so the user sees the answer as it’s written instead of waiting for all of it. - Error handling. If the AI returns an error (for example, you hit the free tier’s limit) or no reply at all, the server removes the unanswered question from the history and tells the user to try again.
Step 3: Build the chat page
Create index.html in the same folder:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Study Buddy</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; background: #f6f5ff; }
main { max-width: 640px; margin: 0 auto; padding: 24px 16px; }
#log { display: flex; flex-direction: column; min-height: 300px; }
.bubble { margin-bottom: 10px; padding: 10px 14px; border-radius: 14px; max-width: 85%; white-space: pre-wrap; line-height: 1.45; }
.user { align-self: flex-end; background: #5857ff; color: #fff; }
.bot { align-self: flex-start; background: #fff; border: 1px solid #e2e2f0; }
form { display: flex; margin-top: 16px; }
input { flex: 1; margin-right: 8px; padding: 10px 12px; font-size: 16px; border: 1px solid #c9c8ff; border-radius: 10px; }
button { padding: 10px 18px; font-size: 16px; border: 0; border-radius: 10px; background: #111; color: #fff; }
button:disabled { opacity: 0.5; }
</style>
</head>
<body>
<main>
<h1>Study Buddy</h1>
<div id="log"></div>
<form id="form">
<input id="input" autocomplete="off" placeholder="Ask a coding question..." required>
<button>Send</button>
</form>
</main>
<script>
const log = document.getElementById("log");
const form = document.getElementById("form");
const input = document.getElementById("input");
const button = form.querySelector("button");
let conversationId = null;
function addBubble(role, text = "") {
const bubble = document.createElement("div");
bubble.className = `bubble ${role}`;
bubble.textContent = text; // textContent, never innerHTML, so replies can't inject HTML
log.append(bubble);
return bubble;
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
const message = input.value.trim();
if (!message) return;
input.value = "";
addBubble("user", message);
const reply = addBubble("bot");
button.disabled = true;
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message, conversationId }),
});
if (!response.ok) {
reply.textContent = await response.text();
return;
}
conversationId = response.headers.get("X-Conversation-Id");
// Read the reply piece by piece as the server streams it.
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
reply.textContent += decoder.decode(value, { stream: true });
}
} catch {
reply.textContent = "Couldn't reach the server. Is it running?";
} finally {
button.disabled = false;
input.focus();
}
});
</script>
</body>
</html>The interesting part is the loop at the end. Instead of waiting for response.text(), it reads the response body piece by piece with getReader() and adds each piece to the chat bubble, so the reply appears as it’s written. The page uses textContent, never innerHTML, so a reply can’t inject HTML or scripts into the page.
Step 4: Run it
node server.js
Open http://localhost:3000 in your browser and ask something like “What is a closure in JavaScript?” Then ask “Can you show me another example?” The second answer builds on the first, because the server sent the whole conversation.
Run it free and offline with Ollama
Prefer no account and no limits? Ollama runs open models on your own computer, so your conversations never leave it. It needs a reasonably modern computer (about 8 GB of memory or more) and downloads a model of a couple of gigabytes; replies are slower on older laptops.
- Install Ollama from
ollama.comand start it. - Download a small model and the Ollama library: run
ollama pull llama3.2, thennpm install ollama. - In
server.js, replace everything from// --- AI providerto// --- end of AI provider ---with the block below. No API key is needed.
// --- AI provider: swap this block to use a different AI ---
import ollama from "ollama";
// Runs on your own computer through Ollama: no account, no key, no cost.
const MODEL = "llama3.2";
// Sends the conversation to the AI, calls onText with each piece of the reply
// as it arrives, and returns the full reply.
async function streamReply(history, onText) {
const stream = await ollama.chat({
model: MODEL,
messages: [{ role: "system", content: SYSTEM_PROMPT }, ...history],
stream: true,
});
let reply = "";
for await (const part of stream) {
const text = part.message.content;
reply += text;
onText(text);
}
return reply;
}
// --- end of AI provider ---Ollama takes the system prompt as the first message, with the role "system", and uses the same user/assistant roles as our history, so no conversion is needed. Restart the server and chat as before. The first reply takes a few extra seconds while Ollama loads the model into memory; after that, replies start quickly.
Prefer Claude? Swap in a paid model
Paid APIs such as Anthropic’s Claude have no standing free tier, but they’re a short swap. Create an account and API key in the Claude Console at platform.claude.com, add billing, set ANTHROPIC_API_KEY the same way as above, run npm install @anthropic-ai/sdk, and replace the AI-provider block with:
// --- AI provider: swap this block to use a different AI ---
import Anthropic from "@anthropic-ai/sdk";
// Reads your API key from the ANTHROPIC_API_KEY environment variable. Paid, per token.
const client = new Anthropic();
const MODEL = "claude-opus-5-5";
// Sends the conversation to the AI, calls onText with each piece of the reply
// as it arrives, and returns the full reply.
async function streamReply(history, onText) {
const stream = client.beta.messages.stream({
model: MODEL,
max_tokens: 16000,
system: SYSTEM_PROMPT,
messages: history,
output_config: { effort: "low" }, // quick, inexpensive replies for chat
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default", // if the model declines, let the API retry on another model
});
stream.on("text", onText);
const message = await stream.finalMessage();
if (message.stop_reason === "refusal") return "";
return message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
}
// --- end of AI provider ---effort: "low" asks the model for quick answers instead of long reasoning, which suits chat and keeps costs down. fallbacks: "default" is a beta feature that retries on another model if the first one declines a request. For a cheaper bot, change MODEL to "claude-haiku-5-5", Anthropic’s smallest current model.
Common errors
| What you see | What it means | Fix |
|---|---|---|
Cannot use import statement outside a module | Node is treating your file as an old-style script | Run npm pkg set type=module |
ERR_MODULE_NOT_FOUND | The AI library isn’t installed in this folder | Run the npm install command for your provider |
An EBADENGINE warning when installing | Your Node.js is older than version 22 | Install the current Node.js LTS release |
| “error 400” or “error 403” | The API key is missing or wrong | Set the key in the same terminal, then restart the server |
| “error 429” | You’ve hit the free tier’s per-minute or per-day limit | Wait a minute, or until the daily limit resets |
ECONNREFUSED with port 11434 | Ollama isn’t running | Start the Ollama app, then try again |
| “error 404” with Ollama | The model hasn’t been downloaded | Run ollama pull llama3.2 |
Choosing a model
The code uses gemini-3.5-flash-lite, a fast, stable Gemini model that Google recommends for new projects and offers on its free tier. Model names change as new versions come out, so if a name stops working, check the models page in Google AI Studio and update MODEL. Every request sends the whole conversation, so very long chats use more of your free quota; a real app would cap how many past messages it sends.
Make it your own
- Change the personality: rewrite
SYSTEM_PROMPTto make an interview coach, a Spanish tutor, or a support bot for your own project. - Render Markdown: models often format answers with Markdown. Show it nicely with a small library, and sanitize the HTML it produces.
- Save conversations: the
Mapdisappears when the server restarts. Store history in a database to keep it. - Before you deploy: add rate limiting and a cap on message length, so one visitor can’t use up your quota.
- Give it tools: LLM APIs can call functions you define, such as looking up a database or the weather. That’s the first step toward an AI agent, the subject of programs like CMU’s Agentic AI program.
From Michael, Hack Reactor ’16: Building one small, working thing teaches more than reading about it ever will. A chatbot is a good first AI project because it touches the parts that matter in real jobs: a server, an API, secrets, streaming, and error handling. Once it works, change one thing at a time and watch what happens. That habit is most of what software development is.
AI Chatbot in JavaScript FAQ
Can I build an AI chatbot for free?
Yes. Google’s Gemini API has a free tier that needs no credit card, which is what this tutorial uses. For something completely free and offline, run an open model on your own computer with Ollama.
Can I build an AI chatbot with just JavaScript?
Yes. This tutorial uses plain JavaScript on both sides: Node.js on the server and a regular web page in the browser, with the AI provider’s official library for the API calls. No frameworks are needed.
Why do I need a server? Can’t the page call the AI directly?
The API key has to stay secret, and anything in browser code is public. The server keeps the key private, stores the conversation, and passes replies to the page.
How does the chatbot remember the conversation?
It doesn’t, by itself: each request starts fresh. The server saves every message and sends the whole conversation with each new request, so the model sees what was said before.
What is a system prompt?
Instructions sent with every request that tell the model how to behave: its role, tone, and rules. Changing the system prompt is the easiest way to customize a chatbot.
Can I switch to a different AI later?
Yes. In this tutorial, everything specific to the AI lives in one block of the server, with ready-made versions for Gemini, Ollama, and Claude. Most other providers work the same way: send the messages and a system prompt, and stream back a reply.
Michael has a diverse background in software engineering, mechanical engineering, economics, and management. After a successful career in mechanical engineering, Michael decided to become a software engineer and attended the Hack Reactor coding bootcamp. Michael enjoys writing about his experiences and helping others start their journeys in software development.
