Build a RAG Chatbot Platform with React & Node
How I built a multi-tenant chatbot SaaS on the PERN stack, using Voyage AI embeddings, pgvector and Claude
What we’re building
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:
- A React dashboard to create and customize bots (name, colors, welcome message, avatar)
- Three ways to add knowledge: pasted text, FAQ pairs, and a website crawler
- Semantic search over that knowledge with Voyage AI embeddings and pgvector
- An embeddable chat widget in plain JavaScript, with no dependencies
- Conversation history, lead capture, and subscription plans with bot limits
Architecture
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 .
Step 1: The database
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:
The vector(1024) size must match your embedding model’s output. voyage-4-lite returns 1024 dimensions by default.
If CREATE EXTENSION vector fails with extension is not available, pgvector isn’t installed on the Postgres server itself. Locally, the easiest fix is the pgvector/pgvector:pg16 Docker image. Managed hosts like Supabase and Neon include it.
Every knowledge chunk carries a bot_id. That one column is what keeps each customer’s content separate from everyone else’s.
Step 2: Create embeddings with Voyage AI
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.
Step 3: Chunk the knowledge and store it
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.
Step 4: Retrieve the right chunks
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.
Step 5: Ask Claude, grounded in the retrieved context
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:
The model is stateless. Your database is the memory. Load the last few messages and send them with every request.
Delimit the knowledge. Wrapping it intags lets you tell Claude to treat it as reference material, not as instructions.
Tell it what to do when it doesn’t know. Without that rule, models tend to fill gaps with plausible guesses.
Keep the API key on the server. The widget never talks to Anthropic or Voyage directly.
Always have a fallback. If retrieval fails or a new bot hasn’t been indexed yet, the bot still answers from the full text.
Step 6: The embeddable widget
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.
Rendering lists and bold text safely
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 and wraps everything else in tags. Only your own markup survives, because anything the model (or a crawled web page) tried to inject was already escaped.
Step 7: The dashboard and three ways to add knowledge
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:
FAQ pairs. A list of question and answer inputs, saved as a JSONB array on the bot and embedded as individual chunks in Step 3.
Conversations page. A list of chats with a transcript view, built from the conversations and messages tables.
Lead capture. An optional pre-chat form collects a visitor’s name, email and phone. An Extract Lead button saves them as a lead, one per conversation.
Crawl a website into the knowledge base
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.
Step 8: Multi-tenancy and plans
This is a multi-tenant app, so two rules apply everywhere:
Every bot-scoped query filters by bot_id. Retrieval only ever searches one bot’s chunks, so one customer’s content can’t enter another customer’s prompt.
Dashboard routes verify ownership first. Before returning conversations or leads, confirm the bot belongs to the logged-in client:
async function verifyBotOwnership ( botId , cl
Comments
No comments yet. Start the discussion.