How to Add RAG to a NodeJS App: A Practical Guide
Add RAG to a Node.js app with LangChain.js, OpenAI embeddings, and pgvector. Four steps: chunk, embed, store vectors, retrieve, and generate answers.
By Galactic News Editorial · Published 2026-11-21T19:29:52+00:00 · Updated 2026-11-21T19:29:52+00:00
How to Add RAG to a NodeJS App: A Practical Guide
Retrieval-augmented generation, or RAG, lets a language model answer questions using your own documents. The model still generates the answer. The difference is that it reads your data first. This guide shows how to add RAG to a NodeJS app with LangChain.js, OpenAI embeddings, and pgvector. It covers the full pipeline: chunking, embedding, storage, retrieval, and generation.
How to Add RAG to a NodeJS App: The Pipeline in Four Steps
RAG has four stages. First, ingestion: documents are loaded, split into chunks, and converted into vector embeddings. Second, storage: embeddings are indexed in a vector database. Third, retrieval: a user question is embedded and the nearest chunks are found by similarity search. Fourth, generation: the retrieved chunks and the question are sent to the model, which writes a grounded answer.
The two halves run at different times. Ingestion runs offline, when content is created or updated, ideally in a background job. Querying runs online, on every user request, and is latency-sensitive. Keep that split in mind when designing the code. The ingestion script and the query endpoint are separate pieces.
LangChain.js is the natural framework choice for Node.js. Version 1 reorganized the packages. The core package defines documents, prompts, and interfaces. The text splitters live in a separate package. The classic chains, file loaders, and in-memory index live in a package called classic. The official migration guide documents this split. Older tutorials that import chains from the main langchain package will fail on version 1.
Step 1: Install Packages and Set Up the Project
Start with a fresh Node.js project using ES modules. LangChain packages are ES modules. Without type module set in package.json, Node treats files as CommonJS and throws an import error.
npm init -y
npm pkg set type=module
npm install @langchain/core @langchain/textsplitters @langchain/classic langchain
npm install @langchain/openai @langchain/pgvector pg dotenvStore the OpenAI key in a .env file. Never commit it. Load it with dotenv at the top of the entry file. The packages break down like this: core holds the document and prompt types, textsplitters holds the chunking code, classic holds the retrieval chains and loaders, openai holds the model and embedding bindings, and pgvector holds the Postgres vector store.
For the database, use PostgreSQL with the pgvector extension. Supabase ships pgvector pre-installed. A self-hosted Postgres needs the extension installed and enabled with CREATE EXTENSION IF NOT EXISTS vector. The embedding model in this guide is text-embedding-3-small, which produces 1,536-dimension vectors. The database column must match that size.
Step 2: Chunk Documents and Generate Embeddings
Chunking is the most important tuning decision in a RAG system. Chunks that are too large dilute the meaning. Chunks that are too small lose context. A practical default is 800 characters with 120 characters of overlap, or about 500 tokens with 10 percent overlap. Tune from there based on what your queries miss.
LangChain's RecursiveCharacterTextSplitter is the standard tool for this. It splits text on separators in order: paragraphs, then lines, then sentences, then words. That order keeps each chunk as coherent as possible.
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 800,
chunkOverlap: 120,
});
const docs = await splitter.createDocuments([rawText]);Next, turn each chunk into an embedding. OpenAIEmbeddings with text-embedding-3-small is the common default. It is cheap and fast. The cost is 2 cents per million input tokens, which works out to roughly 750,000 words for two cents. Batch the embedding calls instead of embedding one chunk at a time.
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
apiKey: process.env.OPENAI_API_KEY,
});One rule is absolute: the embedding model used at ingestion and the one used at query time must be identical. Switching models later means re-indexing the entire collection. Pick the model once and record the choice in the project readme.
Step 3: Store Vectors in pgvector
PGVectorStore from the pgvector package creates the table if needed, embeds documents, and stores vectors with metadata. The setup is a few lines.
import pg from "pg";
import { PGVectorStore } from "@langchain/pgvector";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const vectorStore = await PGVectorStore.initialize(embeddings, {
pool,
tableName: "rag_documents",
columns: {
idColumnName: "id",
vectorColumnName: "vector",
contentColumnName: "content",
metadataColumnName: "metadata",
},
distanceStrategy: "cosine",
});
await vectorStore.addDocuments(docs);For a hand-rolled setup without LangChain's store, the SQL is simple. Create a documents table and an embeddings table, or one table holding both. The vector column is declared as vector(1536) to match the embedding model. Add an HNSW index for approximate nearest-neighbour search. HNSW is the current default over the older IVFFlat index. It builds before data exists and avoids a post-insert clustering pass.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE embeddings (
id BIGSERIAL PRIMARY KEY,
content TEXT NOT NULL,
source TEXT,
embedding vector(1536)
);
CREATE INDEX ON embeddings USING hnsw (embedding vector_cosine_ops);Always store the source of each chunk in metadata. The source name, page, or URL is what lets the app cite its answers later. A RAG answer without a source is a claim the user cannot check.
Step 4: Retrieve Context and Generate the Answer
At query time, turn the vector store into a retriever. The retriever embeds the question and returns the top-k nearest chunks. Four is a good starting value for k. Five works when answers need broader context.
const retriever = vectorStore.asRetriever({ k: 4 });
const chunks = await retriever.invoke("How does pgvector semantic search work?");Then wire retrieval and generation together. LangChain's LCEL style builds a chain that pulls context, formats a prompt, and calls the model. The prompt must tell the model to answer only from the retrieved context and to say when the context does not contain the answer. That instruction is the main defense against hallucination.
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
const model = new ChatOpenAI({ model: "gpt-4o" });
const prompt = ChatPromptTemplate.fromMessages([
["system", "Answer using only the context below. If the context does not contain the answer, say so."],
["human", "Context:\n{context}\n\nQuestion: {question}"],
]);For a first version, the in-memory MemoryVectorStore works well. It needs no database. Swap in pgvector when the document count grows or when data must persist between restarts. The retriever interface is the same either way, so the swap is small.
Choosing a Vector Store
The store choice depends on scale and on what the team already runs. The trade-offs are practical, not ideological.
| Store | Best for | Strength | Trade-off |
|---|---|---|---|
| MemoryVectorStore | Prototypes and tests | Zero setup, same retriever interface | Data lost on restart |
| pgvector | Apps already on Postgres | Vectors live next to relational data and permissions | Requires Postgres and the extension |
| Supabase pgvector | Small teams without DB ops | Managed Postgres with pgvector pre-installed | Tied to a hosted service |
| Pinecone | Large scale or managed search | Fully managed index, no DB ops | Separate service and separate bill |
| Chroma | Local development | Simple local vector database | Less suited to multi-tenant production |
Most Node.js apps already run Postgres. That makes pgvector the default choice. It keeps tenant IDs, permissions, and timestamps queryable in plain SQL in the same transaction as the vectors.
Common Mistakes and How to Avoid Them
Five mistakes cause most RAG failures. Each one is easy to prevent.
- Wrong chunk size. Start at 800 characters with 120 overlap. Measure retrieval quality before changing it.
- Embedding model mismatch. Use the same model for ingestion and retrieval, or re-index everything.
- No source metadata. Store the source with every chunk so answers can be cited and checked.
- No grounding instruction. Tell the model to answer only from context and to admit when it cannot.
- Too many chunks in the prompt. More context is not better. Four to five chunks is the usual range. Extra chunks add noise and cost.
Test retrieval separately from generation. Run a set of known questions against the retriever and check whether the right chunks come back. If retrieval is wrong, no prompt will fix the answer. Fix the chunking or the embedding first.
Bottom Line
Adding RAG to a NodeJS app is four steps: split documents into chunks, embed them, store the vectors, and retrieve before generating. LangChain.js provides the pieces, and pgvector provides storage that lives next to the rest of the app's data. Start with the in-memory store for a prototype. Move to pgvector for production. Keep chunk size near 800 characters, keep the embedding model fixed, and always tell the model to answer only from the retrieved context.