How I built a multi-tenant chatbot SaaS on the PERN stack, using Voyage AI embeddings, pgvector and Claude
A platform where a business signs up, creates a chatbot, teaches it from its own content, and embeds it on its website with a single script tag. Visitors chat with the bot, and the business reviews conversations and leads in a dashboard.
The bot doesn’t guess. It uses retrieval-augmented generation (RAG): it finds the pieces of the business’s own content that match the visitor’s question, hands them to Claude, and Claude answers from that material.
The finished project has:
Visitor's website
└─ <script> tag loads the chat widget
│ POST /api/chat/:botId/message
▼
Node + Express API
1. load the bot and the last 10 messages
2. embed the question (Voyage AI)
3. find the 5 closest chunks (pgvector)
4. build the prompt and call Claude
5. save and return the reply
│
▼
PostgreSQL + pgvector (bots, conversations, messages, knowledge_chunks)
Prerequisites: Node 18 or newer, Postgres with the pgvector extension, an Anthropic API key and a Voyage AI API key. Put them in your .env as ANTHROPIC_API_KEY and VOYAGE_API_KEY.
Enable pgvector and create four tables. This is a trimmed version of the real schema:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE bots (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
client_id UUID NOT NULL,
name VARCHAR(255) NOT NULL,
system_instructions TEXT,
knowledge_base TEXT,
faqs JSONB DEFAULT '[]',
is_active BOOLEAN DEFAULT true
);
CREATE TABLE knowledge_chunks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
bot_id UUID NOT NULL REFERENCES bots(id) ON DELETE CASCADE,
content TEXT NOT NULL,
embedding vector(1024),
source_type VARCHAR(20) NOT NULL DEFAULT 'paragraph'
);
CREATE INDEX ON knowledge_chunks(bot_id);
CREATE TABLE conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
bot_id UUID NOT NULL REFERENCES bots(id) ON DELETE CASCADE,
visitor_id VARCHAR(255),
started_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
role VARCHAR(20) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
Two things to know:
Every knowledge chunk carries a bot_id. That one column is what keeps each customer’s content separate from everyone else’s.
An embedding turns text into a list of numbers so that texts with similar meaning end up close together. Wrap the Voyage API in one small function:
const VOYAGE_URL = 'https://api.voyageai.com/v1/embeddings';
async function embedTexts(texts, inputType = 'document') {
const res = await fetch(VOYAGE_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.VOYAGE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
input: texts,
model: 'voyage-4-lite',
input_type: inputType,
}),
});
const data = await res.json();
if (!res.ok) throw new Error('Embedding request failed');
return data.data.map((item) => item.embedding);
}
The input_type matters. Use document when you embed your knowledge and query when you embed the visitor’s question. Voyage tunes the vector for each side of the search, which improves retrieval quality.
Don’t embed a whole document as one vector. A long text averages many topics, so it matches no single question well. Split it into chunks of roughly 300–400 tokens (about 1,500 characters), breaking on paragraphs so related sentences stay together:
function chunkText(text, maxChars = 1500) {
const paragraphs = text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
const chunks = [];
let current = '';
for (const para of paragraphs) {
const candidate = current ? `${current}\n\n${para}` : para;
if (candidate.length > maxChars && current) {
chunks.push(current);
current = para;
} else {
current = candidate;
}
}
if (current) chunks.push(current);
return chunks; // the full version also hard-splits any single paragraph over maxChars
}
FAQ pairs are different: each one is already a complete unit, so each becomes its own chunk. Embedding the question and answer together means the chunk matches whether the visitor’s phrasing resembles the question or the answer.
async function reindexBot(botId, knowledgeBase, faqs = []) {
await pool.query('DELETE FROM knowledge_chunks WHERE bot_id = $1', [botId]);
const chunks = [
...chunkText(knowledgeBase || '').map((content) => ({ content, sourceType: 'paragraph' })),
...faqs.map((f) => ({ content: `Q: ${f.question}\nA: ${f.answer}`, sourceType: 'faq' })),
];
if (chunks.length === 0) return;
const embeddings = await embedTexts(chunks.map((c) => c.content), 'document');
for (let i = 0; i < chunks.length; i++) {
await pool.query(
`INSERT INTO knowledge_chunks (bot_id, content, embedding, source_type)
VALUES ($1, $2, $3::vector, $4)`,
[botId, chunks[i].content, `[${embeddings[i].join(',')}]`, chunks[i].sourceType]
);
}
}
Call reindexBot whenever a bot’s knowledge or FAQs are saved, and run it in the background so the dashboard doesn’t wait on the embedding API. Embedding APIs cap how many texts you can send per request, so batch the input if a bot has a very large knowledge base.
At chat time, embed the question as a query and ask Postgres for the closest chunks, for this bot only:
async function searchChunks(botId, queryEmbedding, limit = 5) {
const { rows } = await pool.query(
`SELECT content FROM knowledge_chunks
WHERE bot_id = $1
ORDER BY embedding <-> $2::vector
LIMIT $3`,
[botId, `[${queryEmbedding.join(',')}]`, limit]
);
return rows.map((r) => r.content);
}
The <-> operator is L2 (Euclidean) distance. pgvector also has <=> for cosine distance and <#> for negative inner product. Voyage’s embeddings are normalized to unit length, so all three rank results the same way. Whichever operator you choose, any approximate-nearest-neighbor index you add later has to match it.
Now put it together in the chat endpoint. The flow is: load the bot, load recent history, retrieve, build the prompt, call Claude, save the reply.
app.post('/api/chat/:botId/message', async (req, res) => {
const { botId } = req.params;
const { message, conversationId, visitorId } = req.body;
const bot = await getActiveBot(botId); // return 404 if the bot is inactive
const conversation = await getOrCreateConversation(botId, visitorId, conversationId);
const history = await getRecentMessages(conversation.id, 10); // [{ role, content }]
await saveMessage(conversation.id, 'user', message);
// Retrieve. Fall back to the full knowledge base if anything goes wrong.
let context = bot.knowledge_base || '';
try {
if (await hasChunks(botId)) {
const [queryEmbedding] = await embedTexts([message], 'query');
const chunks = await searchChunks(botId, queryEmbedding, 5);
if (chunks.length > 0) context = chunks.join('\n\n---\n\n');
}
} catch (err) {
console.error('Retrieval failed, using the full knowledge base', err);
}
const system = `You are ${bot.name}, a support assistant for this business.
Answer using only the information inside <knowledge>. If the answer isn't there,
say you don't know and offer to connect the visitor with the business.
For simple questions, answer in plain sentences. When listing several items,
use lines starting with a dash and **bold** the key term. Do not use headings.
<knowledge>
${context}
</knowledge>`;
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': process.env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify({
model: 'claude-haiku-4-5-20251001',
max_tokens: 500,
system,
messages: [...history, { role: 'user', content: message }],
}),
});
const data = await response.json();
if (!response.ok) return res.status(502).json({ error: 'The assistant is unavailable' });
const reply = data.content[0].text;
await saveMessage(conversation.id, 'assistant', reply);
res.json({ reply, conversationId: conversation.id });
});
A few choices in there are worth copying:
Customers add the bot to their site with one line:
<script src="https://your-api.example.com/widget.js" data-bot-id="YOUR_BOT_ID"></script>
widget.js is plain JavaScript served by your Node app. It reads its own script tag to find the bot ID and your API’s origin, then fetches the bot’s public config (name, colors, welcome message) and builds the chat bubble:
(async function () {
const script = document.currentScript;
const botId = script.getAttribute('data-bot-id');
const API = new URL(script.src).origin;
const res = await fetch(`${API}/api/chat/${botId}/config`);
if (!res.ok) return; // inactive or unknown bot: render nothing at all
const config = await res.json();
// ...create the launcher button and chat panel from config...
})();
Sending a message is a single fetch to the endpoint from Step 5:
async function send(text) {
const res = await fetch(`${API}/api/chat/${botId}/message`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text, visitorId, conversationId }),
});
const data = await res.json();
conversationId = data.conversationId; // keep the thread going
addMessage('assistant', data.reply);
}
Because this code runs on other people’s websites, keep it small, scope your CSS class names with a prefix, and enable CORS on the public chat routes only.
If you ask Claude for lists and bold text, you have to render them. Set textContent and your visitors see raw ** and - characters. Set innerHTML naively and you’ve created an XSS hole. The fix is to escape first, then format:
const escapeHtml = (s) =>
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const renderInline = (s) => s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
From there, a small loop turns consecutive lines that start with a dash into a
tags. Only your own markup survives, because anything the model (or a crawled web page) tried to inject was already escaped.
The React dashboard is a form over the bots table: name, welcome message, colors, avatar, the knowledge textarea, an FAQ editor, and a live preview of the widget. A few pieces make it feel complete:
Paste a URL and the server crawls same-domain pages with cheerio, strips scripts, navigation and footers, and caps the crawl at 12 pages. It then asks Claude to draft FAQ pairs from the text. Both results land in the form, so the business can edit everything before saving.
Any feature that makes your server fetch a user-supplied URL needs SSRF protection, or someone can point it at your internal network. At minimum, resolve the hostname and refuse private addresses:
const { address } = await dns.promises.lookup(hostname);
if (isPrivateIp(address)) {
throw new Error('Refusing to crawl a private or internal address');
}
That check alone isn’t complete, because fetch follows redirects. Validate each redirect target too, and cap response sizes.
This is a multi-tenant app, so two rules apply everywhere:
async function verifyBotOwnership(botId, clientId) {
const { rows } = await pool.query(
'SELECT 1 FROM bots WHERE id = $1 AND client_id = $2',
[botId, clientId]
);
return rows.length > 0;
}
Subscription plans are a plans table with a bot_limit column, where NULL means unlimited. The check lives on the server, in the create-bot endpoint:
if (limit !== null && currentCount >= limit) {
return res.status(403).json({ error: 'Plan limit reached. Upgrade to create more bots.' });
}
The UI also reads the limit and disables the create button, but that is only a courtesy. The server check is the real enforcement.
Chatbots that talk to the public can get expensive quickly. These changes made the biggest difference:
The core of a RAG chatbot is smaller than it looks: chunk your content, embed it with Voyage, store the vectors in Postgres, search them with pgvector, and let Claude answer from what comes back. Everything else — the widget, the dashboard, plans, leads — is ordinary full-stack work on a PERN app.
If you build your own version, start with Steps 1–5 and test retrieval from a script before you touch any UI. If the right chunk doesn’t show up in the top 5, nothing downstream can fix it.