A step-by-step guide to building a RAG chatbot in Node.js: chunking, embeddings, vector search, prompting an LLM API and streaming answers.

A plain LLM chatbot knows a lot about the world and nothing about your business. Ask it about your refund policy or your product docs and it will either refuse or confidently make something up. Retrieval-Augmented Generation (RAG) fixes that by finding the relevant parts of your own content and handing them to the model with the question. In this guide I show how to build a RAG chatbot with Node.js and LLM APIs, step by step.
I work on AI-powered chatbots, RAG workflows and LLM integrations as a Full Stack and AI Developer at Stackerra, and the structure below is the one I reach for when a project needs a chatbot that answers from its own data.
What RAG actually is
RAG has two phases:
- Indexing (offline). Split your documents into chunks, turn each chunk into an embedding (a vector of numbers that captures its meaning) and store the vectors.
- Answering (per question). Embed the user's question, find the chunks with the most similar vectors, put those chunks into the prompt, and ask the LLM to answer using only that context.
The model doesn't need retraining. When your content changes, you re-index the changed documents and the chatbot knows about it immediately.

Index once: chunk, embed, store. Per question: embed, search, prompt, answer with sources.
When to use RAG and when not to
RAG is a good fit when:
- answers must come from your documents: help centres, policies, product manuals, internal wikis
- content changes often enough that fine-tuning would go stale
- you need to show sources for an answer
It is not the right tool when the task is about style or format rather than knowledge (prompting or fine-tuning handles that), or when the "documents" are really structured data better answered with a database query.
The stack
For this guide:
- Node.js with ES modules
- Express for the chat API
- An LLM API for chat completions and an embeddings API for vectors. The examples use the OpenAI Node SDK, but the same structure works with other providers.
- A vector store. I start with an in-memory store to show the idea, then cover production options.
npm install express openai
Step 1: Load and chunk your documents
LLMs have a limited context window, and retrieval works best on focused pieces of text. So we split documents into overlapping chunks:
export function chunkText(text, { size = 800, overlap = 150 } = {}) {
const clean = text.replace(/\s+/g, ' ').trim();
const chunks = [];
let start = 0;
while (start < clean.length) {
let end = Math.min(start + size, clean.length);
// try to end on a sentence boundary
const lastPeriod = clean.lastIndexOf('. ', end);
if (lastPeriod > start + size * 0.5) end = lastPeriod + 1;
chunks.push(clean.slice(start, end).trim());
if (end >= clean.length) break;
start = end - overlap;
}
return chunks;
}
Practical tips on chunking:
- Overlap keeps a sentence that spans two chunks from losing its context.
- Respect structure. For Markdown or HTML, split on headings first, then by size. A chunk that starts mid-table is hard to retrieve.
- Keep metadata with every chunk: source document, title, URL, section. You need it for citations and filtering later.

Overlapping chunks keep sentences that cross a boundary in context.
Step 2: Create embeddings
Each chunk becomes a vector. Batch the calls instead of embedding one chunk at a time:
import OpenAI from 'openai';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const EMBED_MODEL = 'text-embedding-3-small';
export async function embed(texts) {
const res = await client.embeddings.create({ model: EMBED_MODEL, input: texts });
return res.data.map((d) => d.embedding);
}
Use the same embedding model for documents and questions. Vectors from different models are not comparable.
Step 3: Store and search vectors
To understand the mechanics, here is a tiny in-memory vector store using cosine similarity:
function cosine(a, b) {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
na += a[i] * a[i];
nb += b[i] * b[i];
}
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
export class MemoryVectorStore {
constructor() { this.items = []; }
add(items) { this.items.push(...items); } // { id, text, embedding, metadata }
search(queryEmbedding, k = 5) {
return this.items
.map((item) => ({ ...item, score: cosine(queryEmbedding, item.embedding) }))
.sort((a, b) => b.score - a.score)
.slice(0, k);
}
}
And the indexing script that ties steps 1 to 3 together:
import { readFile } from 'node:fs/promises';
export async function indexDocuments(store, docs) {
for (const doc of docs) {
const text = await readFile(doc.path, 'utf8');
const chunks = chunkText(text);
const vectors = await embed(chunks);
store.add(chunks.map((chunk, i) => ({
id: `${doc.id}-${i}`,
text: chunk,
embedding: vectors[i],
metadata: { title: doc.title, url: doc.url },
})));
}
}
Production vector stores
In-memory search is fine for a demo or a few hundred chunks. For real use, pick a proper store:
- MongoDB Atlas Vector Search if you already use MongoDB, which keeps data and vectors in one place
- PostgreSQL with pgvector if you're on Postgres
- A dedicated vector database when you have very large collections or need advanced filtering
The code structure stays the same. Only the add and search functions change.
Step 4: Build the prompt
This is where a lot of RAG chatbots go wrong. The prompt has to tell the model clearly to use the context and to admit when it doesn't know:
function buildMessages(question, contexts, history = []) {
const contextBlock = contexts
.map((c, i) => `[${i + 1}] (${c.metadata.title})\n${c.text}`)
.join('\n\n');
return [
{
role: 'system',
content:
'You are a helpful assistant for our company. Answer using ONLY the context below. ' +
'If the answer is not in the context, say you don\'t know and suggest contacting support. ' +
'Cite sources like [1], [2]. Keep answers short and clear.\n\n' +
`Context:\n${contextBlock}`,
},
...history.slice(-6),
{ role: 'user', content: question },
];
}
A few rules I stick to:
- Ground strictly. "Only the context" plus an explicit "say you don't know" reduces made-up answers a lot.
- Number the sources so the model can cite them and the UI can link them.
- Limit history. Sending the whole conversation every time wastes tokens and can push the context out of the window.
Step 5: The chat endpoint with streaming
Streaming makes the chatbot feel fast because users see the answer appear immediately:
import express from 'express';
const app = express();
app.use(express.json());
const store = new MemoryVectorStore();
const CHAT_MODEL = 'gpt-4o-mini';
app.post('/api/chat', async (req, res) => {
const { question, history = [] } = req.body;
if (!question || question.length > 2000) {
return res.status(400).json({ error: 'Invalid question' });
}
const [qVector] = await embed([question]);
const contexts = store.search(qVector, 5).filter((c) => c.score > 0.3);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const stream = await client.chat.completions.create({
model: CHAT_MODEL,
messages: buildMessages(question, contexts, history),
temperature: 0.2,
stream: true,
});
for await (const part of stream) {
const token = part.choices[0]?.delta?.content;
if (token) res.write(`data: ${JSON.stringify({ token })}\n\n`);
}
const sources = contexts.map((c, i) => ({ n: i + 1, title: c.metadata.title, url: c.metadata.url }));
res.write(`data: ${JSON.stringify({ done: true, sources })}\n\n`);
res.end();
});
app.listen(3000);
Notice the similarity threshold. If nothing relevant is found, it's better to pass no context and let the system prompt make the model say "I don't know" than to feed it unrelated chunks. A low temperature keeps answers factual.
Step 6: Improve retrieval quality
Once the basic loop works, most quality gains come from retrieval, not from the model:
- Hybrid search. Combine vector similarity with keyword search. Embeddings are great at meaning but can miss exact terms like product codes.
- Query rewriting. In a multi-turn chat, "what about the price?" means nothing on its own. Ask the LLM to rewrite the latest question into a standalone query before retrieval.
- Re-ranking. Retrieve more candidates, say 20, then re-rank them and keep the best 5.
- Metadata filters. Restrict search by product, language or user permissions. This is also how you keep users from retrieving documents they shouldn't see.

Most RAG quality gains come from better retrieval.
Step 7: Production concerns
A chatbot in front of real users needs the same care as any other API:
- Keep API keys on the server. Never call the LLM directly from the browser.
- Rate limit and cap input size to control abuse and cost.
- Cache embeddings for documents and common questions.
- Re-index on change. Hook indexing into your CMS or a scheduled job so answers stay current.
- Log questions and retrieved sources (without sensitive personal data) so you can see where retrieval fails.
- Evaluate. Keep a small set of real questions with expected answers and re-run it whenever you change chunking, prompts or models.
- Respect privacy. Be deliberate about which documents go into the index and what you send to third-party APIs.
Conclusion
A RAG chatbot is a pipeline more than a model: chunk your content well, embed it, retrieve the right pieces, and prompt the LLM to answer only from them, with sources. Node.js handles all of it comfortably, from indexing scripts to a streaming Express endpoint, and most improvements come from better retrieval rather than a bigger model.
If you want an AI chatbot that answers from your own documents and fits into your existing product, let's talk.