{"slug": "build-a-rag-chatbot-platform-with-react-node", "title": "Build a RAG Chatbot Platform with React & Node", "summary": "A developer built a multi-tenant RAG chatbot SaaS on the PERN stack (PostgreSQL with pgvector, Express, React, Node), using Voyage AI embeddings and Anthropic's Claude to answer visitor questions from each business's own content. The system chunks knowledge into roughly 300–400-token paragraphs, embeds documents and queries with Voyage's voyage-4-lite model using distinct input types, retrieves the five closest chunks per bot via pgvector, and scopes every chunk by bot_id to keep tenants isolated. The bot is embedded on customer sites through a single script tag, with conversations and leads surfaced in a dashboard.", "body_md": "How I built a multi-tenant chatbot SaaS on the PERN stack, using Voyage AI embeddings, pgvector and Claude\n\nA 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.\n\nThe 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.\n\nThe finished project has:\n\n```\nVisitor's website\n  └─ <script> tag loads the chat widget\n        │  POST /api/chat/:botId/message\n        ▼\nNode + Express API\n  1. load the bot and the last 10 messages\n  2. embed the question (Voyage AI)\n  3. find the 5 closest chunks (pgvector)\n  4. build the prompt and call Claude\n  5. save and return the reply\n        │\n        ▼\nPostgreSQL + pgvector  (bots, conversations, messages, knowledge_chunks)\n```\n\n**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**.\n\nEnable pgvector and create four tables. This is a trimmed version of the real schema:\n\n```\nCREATE EXTENSION IF NOT EXISTS vector;\n\nCREATE TABLE bots (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  client_id UUID NOT NULL,\n  name VARCHAR(255) NOT NULL,\n  system_instructions TEXT,\n  knowledge_base TEXT,\n  faqs JSONB DEFAULT '[]',\n  is_active BOOLEAN DEFAULT true\n);\n\nCREATE TABLE knowledge_chunks (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  bot_id UUID NOT NULL REFERENCES bots(id) ON DELETE CASCADE,\n  content TEXT NOT NULL,\n  embedding vector(1024),\n  source_type VARCHAR(20) NOT NULL DEFAULT 'paragraph'\n);\nCREATE INDEX ON knowledge_chunks(bot_id);\n\nCREATE TABLE conversations (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  bot_id UUID NOT NULL REFERENCES bots(id) ON DELETE CASCADE,\n  visitor_id VARCHAR(255),\n  started_at TIMESTAMP DEFAULT NOW()\n);\n\nCREATE TABLE messages (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,\n  role VARCHAR(20) NOT NULL,\n  content TEXT NOT NULL,\n  created_at TIMESTAMP DEFAULT NOW()\n);\n```\n\nTwo things to know:\n\nEvery knowledge chunk carries a bot_id. That one column is what keeps each customer’s content separate from everyone else’s.\n\nAn 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:\n\n``` js\nconst VOYAGE_URL = 'https://api.voyageai.com/v1/embeddings';\n\nasync function embedTexts(texts, inputType = 'document') {\n  const res = await fetch(VOYAGE_URL, {\n    method: 'POST',\n    headers: {\n      Authorization: `Bearer ${process.env.VOYAGE_API_KEY}`,\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      input: texts,\n      model: 'voyage-4-lite',\n      input_type: inputType,\n    }),\n  });\n\n  const data = await res.json();\n  if (!res.ok) throw new Error('Embedding request failed');\n  return data.data.map((item) => item.embedding);\n}\n```\n\nThe **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.\n\nDon’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:\n\n``` js\nfunction chunkText(text, maxChars = 1500) {\n  const paragraphs = text.split(/\\n\\s*\\n/).map((p) => p.trim()).filter(Boolean);\n  const chunks = [];\n  let current = '';\n\n  for (const para of paragraphs) {\n    const candidate = current ? `${current}\\n\\n${para}` : para;\n    if (candidate.length > maxChars && current) {\n      chunks.push(current);\n      current = para;\n    } else {\n      current = candidate;\n    }\n  }\n  if (current) chunks.push(current);\n  return chunks; // the full version also hard-splits any single paragraph over maxChars\n}\n```\n\nFAQ 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.\n\n```\nasync function reindexBot(botId, knowledgeBase, faqs = []) {\n  await pool.query('DELETE FROM knowledge_chunks WHERE bot_id = $1', [botId]);\n\n  const chunks = [\n    ...chunkText(knowledgeBase || '').map((content) => ({ content, sourceType: 'paragraph' })),\n    ...faqs.map((f) => ({ content: `Q: ${f.question}\\nA: ${f.answer}`, sourceType: 'faq' })),\n  ];\n  if (chunks.length === 0) return;\n\n  const embeddings = await embedTexts(chunks.map((c) => c.content), 'document');\n\n  for (let i = 0; i < chunks.length; i++) {\n    await pool.query(\n      `INSERT INTO knowledge_chunks (bot_id, content, embedding, source_type)\n       VALUES ($1, $2, $3::vector, $4)`,\n      [botId, chunks[i].content, `[${embeddings[i].join(',')}]`, chunks[i].sourceType]\n    );\n  }\n}\n```\n\nCall **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.\n\nAt chat time, embed the question as a query and ask Postgres for the closest chunks, for this bot only:\n\n```\nasync function searchChunks(botId, queryEmbedding, limit = 5) {\n  const { rows } = await pool.query(\n    `SELECT content FROM knowledge_chunks\n     WHERE bot_id = $1\n     ORDER BY embedding <-> $2::vector\n     LIMIT $3`,\n    [botId, `[${queryEmbedding.join(',')}]`, limit]\n  );\n  return rows.map((r) => r.content);\n}\n```\n\nThe <-> 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.\n\nNow 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.\n\n``` js\napp.post('/api/chat/:botId/message', async (req, res) => {\n  const { botId } = req.params;\n  const { message, conversationId, visitorId } = req.body;\n\n  const bot = await getActiveBot(botId); // return 404 if the bot is inactive\n  const conversation = await getOrCreateConversation(botId, visitorId, conversationId);\n  const history = await getRecentMessages(conversation.id, 10); // [{ role, content }]\n  await saveMessage(conversation.id, 'user', message);\n\n  // Retrieve. Fall back to the full knowledge base if anything goes wrong.\n  let context = bot.knowledge_base || '';\n  try {\n    if (await hasChunks(botId)) {\n      const [queryEmbedding] = await embedTexts([message], 'query');\n      const chunks = await searchChunks(botId, queryEmbedding, 5);\n      if (chunks.length > 0) context = chunks.join('\\n\\n---\\n\\n');\n    }\n  } catch (err) {\n    console.error('Retrieval failed, using the full knowledge base', err);\n  }\n\n  const system = `You are ${bot.name}, a support assistant for this business.\nAnswer using only the information inside <knowledge>. If the answer isn't there,\nsay you don't know and offer to connect the visitor with the business.\nFor simple questions, answer in plain sentences. When listing several items,\nuse lines starting with a dash and **bold** the key term. Do not use headings.\n\n<knowledge>\n${context}\n</knowledge>`;\n\n  const response = await fetch('https://api.anthropic.com/v1/messages', {\n    method: 'POST',\n    headers: {\n      'x-api-key': process.env.ANTHROPIC_API_KEY,\n      'anthropic-version': '2023-06-01',\n      'content-type': 'application/json',\n    },\n    body: JSON.stringify({\n      model: 'claude-haiku-4-5-20251001',\n      max_tokens: 500,\n      system,\n      messages: [...history, { role: 'user', content: message }],\n    }),\n  });\n\n  const data = await response.json();\n  if (!response.ok) return res.status(502).json({ error: 'The assistant is unavailable' });\n\n  const reply = data.content[0].text;\n  await saveMessage(conversation.id, 'assistant', reply);\n  res.json({ reply, conversationId: conversation.id });\n});\n```\n\nA few choices in there are worth copying:\n\nCustomers add the bot to their site with one line:\n\n```\n<script src=\"https://your-api.example.com/widget.js\" data-bot-id=\"YOUR_BOT_ID\"></script>\n```\n\n**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:\n\n``` js\n(async function () {\n  const script = document.currentScript;\n  const botId = script.getAttribute('data-bot-id');\n  const API = new URL(script.src).origin;\n\n  const res = await fetch(`${API}/api/chat/${botId}/config`);\n  if (!res.ok) return; // inactive or unknown bot: render nothing at all\n  const config = await res.json();\n  // ...create the launcher button and chat panel from config...\n})();\n```\n\nSending a message is a single fetch to the endpoint from Step 5:\n\n``` js\nasync function send(text) {\n  const res = await fetch(`${API}/api/chat/${botId}/message`, {\n    method: 'POST',\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify({ message: text, visitorId, conversationId }),\n  });\n  const data = await res.json();\n  conversationId = data.conversationId; // keep the thread going\n  addMessage('assistant', data.reply);\n}\n```\n\nBecause 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.\n\nIf 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:\n\n``` js\nconst escapeHtml = (s) =>\n  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\nconst renderInline = (s) => s.replace(/\\*\\*(.+?)\\*\\*/g, '<strong>$1</strong>');\n```\n\nFrom there, a small loop turns consecutive lines that start with a dash into a\n\ntags. Only your own markup survives, because anything the model (or a crawled web page) tried to inject was already escaped.\n\nThe 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:\n\nPaste 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.\n\nAny 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:\n\n```\nconst { address } = await dns.promises.lookup(hostname);\nif (isPrivateIp(address)) {\n  throw new Error('Refusing to crawl a private or internal address');\n}\n```\n\nThat check alone isn’t complete, because fetch follows redirects. Validate each redirect target too, and cap response sizes.\n\nThis is a multi-tenant app, so two rules apply everywhere:\n\n```\nasync function verifyBotOwnership(botId, clientId) {\n  const { rows } = await pool.query(\n    'SELECT 1 FROM bots WHERE id = $1 AND client_id = $2',\n    [botId, clientId]\n  );\n  return rows.length > 0;\n}\n```\n\nSubscription 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:\n\n```\nif (limit !== null && currentCount >= limit) {\n  return res.status(403).json({ error: 'Plan limit reached. Upgrade to create more bots.' });\n}\n```\n\nThe UI also reads the limit and disables the create button, but that is only a courtesy. The server check is the real enforcement.\n\nChatbots that talk to the public can get expensive quickly. These changes made the biggest difference:\n\nThe 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.\n\nIf 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.", "url": "https://wpnews.pro/news/build-a-rag-chatbot-platform-with-react-node", "canonical_source": "https://dev.to/da_faq/build-a-rag-chatbot-platform-with-react-node-8am", "published_at": "2026-11-30 05:36:08+00:00", "updated_at": "2026-11-30 05:45:53.441867+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "generative-ai", "ai-agents", "ai-tools"], "entities": ["Voyage AI", "Anthropic", "Claude", "pgvector", "PostgreSQL", "Node.js", "Express", "React"], "also_reported_by": [], "takeaway": "Chunk knowledge into ~1,500-character paragraph-aligned pieces and embed documents with input_type 'document' but queries with 'query', then retrieve the top 5 chunks per bot filtered by bot_id for tenant isolation.", "recommendation": {"advice": "Split knowledge into paragraph-aligned chunks of about 1,500 characters and use Voyage's separate document and query input types to improve retrieval quality.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/build-a-rag-chatbot-platform-with-react-node", "markdown": "https://wpnews.pro/news/build-a-rag-chatbot-platform-with-react-node.md", "text": "https://wpnews.pro/news/build-a-rag-chatbot-platform-with-react-node.txt", "jsonld": "https://wpnews.pro/news/build-a-rag-chatbot-platform-with-react-node.jsonld"}}