Architecture Overview
Technical Overview for Engineersβ
This document provides a technical overview of NetPad's architecture, key patterns, and where things live in the codebase.
Tech Stackβ
| Layer | Technology | Notes |
|---|---|---|
| Framework | Next.js 14+ (App Router) | Required |
| UI Library | React 18+ | Required |
| Component Library | Material-UI (MUI) 5 | Prefer over Tailwind |
| Language | TypeScript | Strict typing required |
| Database | MongoDB Atlas | Only supported database |
| DB Driver | MongoDB Driver 6.5+ | Minimum version |
| Vector Search | MongoDB Atlas Vector Search | For RAG features |
| AI/LLM | Centralized provider | Ollama β OpenAI β OpenRouter |
| Workflow Editor | ReactFlow | Visual DAG editor |
High-Level Architectureβ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β NetPad Platform β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββ βββββββββββββββββ βββββββββββββββββ ββββββββββββ β
β β Forms β β Workflows β β Data Mgmt β β AI β β
β β β β β β β β β β
β β β’ Builder β β β’ Visual β β β’ Browser β β β’ Conv. β β
β β β’ WYSIWYG β β Editor β β β’ Connection β β Forms β β
β β β’ 30+ Fields β β β’ 25+ Nodes β β Vault β β β’ 15+ β β
β β β’ Converstnl β β β’ Triggers β β β’ Import/ β β Agents β β
β β β’ Analytics β β β’ Execution β β Export β β β’ RAG β β
β β β β Engine β β β β β β
β βββββββββββββββββ βββββββββββββββββ βββββββββββββββββ ββββββββββββ β
β β β β β β
β ββββββββββββββββββββ΄βββββββββββββββββββ΄βββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β Platform Services ββ
β β Organizations β Projects β Auth β Billing β Permissions β API ββ
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β MongoDB Integration ββ
β β Atlas β’ Self-hosted β’ Atlas Data API ββ
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Repository Structureβ
netpad-3/
βββ src/ # Main Next.js application
β βββ app/ # App Router pages and API routes
β β βββ api/ # 165+ API endpoints
β β βββ (dashboard)/ # Dashboard routes
β β βββ (public)/ # Public routes
β β
β βββ components/ # React components
β β βββ FormBuilder/ # Form building UI (WYSIWYG)
β β βββ WorkflowEditor/ # Workflow building UI (ReactFlow)
β β βββ ConversationalForm/# AI chat interface
β β βββ DataBrowser/ # Data exploration UI
β β βββ Navigation/ # Application-centric nav
β β
β βββ lib/ # Core libraries
β β βββ ai/ # AI service layer, agents, RAG
β β βββ platform/ # Database connections (SERVER ONLY)
β β βββ conversational/ # Conversation state management
β β βββ storage/ # Blob storage utilities
β β
β βββ hooks/ # Client-side React hooks
β βββ types/ # TypeScript definitions
β
βββ packages/ # NPM packages (@netpad/*)
β βββ templates/ # @netpad/templates
β βββ mcp-server/ # MCP tools for AI assistants
β βββ cli/ # CLI package (active)
β
βββ docs/ # Documentation (Docusaurus)
Core Modulesβ
Forms Systemβ
src/components/FormBuilder/ # Visual form builder
βββ Canvas/ # WYSIWYG editing surface
βββ FieldPalette/ # Field type picker
βββ FieldConfig/ # Field property editor
βββ Preview/ # Form preview modes
βββ ConditionalLogic/ # Logic rule builder
src/lib/platform/
βββ forms.ts # Form CRUD operations
βββ submissions.ts # Submission handling
βββ validation.ts # Server-side validation
Key Concepts:
- Forms have two modes: Traditional (field-based) and Conversational (AI chat)
- Conditional logic controls field visibility
- Computed fields calculate from other field values
- Forms are scoped to Applications
Workflows Systemβ
src/components/WorkflowEditor/ # Visual workflow builder
βββ Canvas/ # ReactFlow canvas
βββ NodePalette/ # Node type picker
βββ NodeConfig/ # Node property editor
βββ ExecutionViewer/ # Run history display
src/lib/platform/
βββ workflows.ts # Workflow CRUD
βββ execution.ts # Execution engine
βββ nodes/ # Node type implementations
Key Concepts:
- Workflows are directed acyclic graphs (DAGs)
- Triggered by: form submission, webhook, schedule, manual
- Nodes process data and pass to next node
- Execution is async with queue management
AI/Conversational Systemβ
src/lib/ai/
βββ aiService.ts # Centralized LLM operations
βββ providers/ # Provider implementations
β βββ ollama.ts
β βββ openai.ts
β βββ openrouter.ts
βββ agents/ # AI agents
β βββ formGenerator.ts
β βββ fieldOptimizer.ts
β βββ complianceChecker.ts
βββ rag/ # RAG implementation
βββ vectorStore.ts
βββ retriever.ts
βββ embedding.ts
src/components/ConversationalForm/
βββ ChatInterface/ # Chat UI
βββ MessageBubble/ # Message display
βββ TopicProgress/ # Progress tracker
βββ DataExtraction/ # Extracted data display
Key Concepts:
- All LLM calls go through centralized
aiService - Provider priority: Ollama β OpenAI β OpenRouter
- RAG uses MongoDB Atlas Vector Search
- Conversational forms extract structured data from natural language
Critical Architecture Rulesβ
1. Client/Server Boundaryβ
// β WRONG - Will cause build error
// In a client component:
import { db } from '@/lib/platform/db';
// β
CORRECT - Use API routes
// In a client component:
const response = await fetch('/api/forms');
Why: MongoDB driver uses native modules that can't run in browser.
2. Centralized LLM Configurationβ
// β WRONG - Hardcoded model
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini', // Don't do this!
messages: [...]
});
// β
CORRECT - Use centralized service
import { aiService } from '@/lib/ai/aiService';
const response = await aiService.complete({
messages: [...],
// Model selected automatically from provider config
});
Why: Ensures metrics tracking, respects user's provider preference (Ollama vs OpenAI).
3. Batch Operations for Formsβ
// β WRONG - Only adds last field
for (const field of fields) {
onAddField(field); // Triggers dialog each time
}
// β
CORRECT - Batch add
onAddTemplate(fields); // Adds all at once
Why: onAddField opens a dialog, loop causes repeated dialogs.
4. MongoDB Versionβ
// Minimum required: MongoDB 6.5+
// Required for:
// - Atlas Vector Search
// - Latest aggregation features
// - Performance improvements
API Structureβ
Endpoint Organizationβ
/api/
βββ forms/ # Form management (~40 endpoints)
β βββ route.ts # GET (list), POST (create)
β βββ [formId]/
β β βββ route.ts # GET, PUT, DELETE
β β βββ submissions/ # Submission handling
β β βββ analytics/ # Form analytics
β βββ templates/ # Template operations
β
βββ workflows/ # Workflow management (~15 endpoints)
β βββ route.ts
β βββ [workflowId]/
β β βββ route.ts
β β βββ execute/ # Trigger execution
β β βββ history/ # Execution history
β βββ nodes/ # Node type definitions
β
βββ organizations/ # Org management (~30 endpoints)
β βββ route.ts
β βββ [orgId]/
β β βββ members/
β β βββ vault/ # Connection vault
β β βββ templates/
β βββ invitations/
β
βββ applications/ # Application management (~10 endpoints)
β βββ route.ts
β βββ [appId]/
β β βββ releases/
β β βββ export/
β βββ import/
β
βββ marketplace/ # Marketplace (~12 endpoints)
β βββ route.ts
β βββ [appId]/
β βββ categories/
β
βββ ai/ # AI operations (~12 endpoints)
β βββ generate/
β βββ optimize/
β βββ agents/
β
βββ rag/ # RAG operations (~5 endpoints)
β βββ documents/
β βββ query/
β
βββ mongodb/ # Database operations (~10 endpoints)
βββ connections/
βββ collections/
βββ query/
Authenticationβ
- Session-based authentication
- Organization-scoped permissions
- Role-based access control (Owner, Admin, Member, Viewer)
Data Modelsβ
Core Entitiesβ
// Organization
interface Organization {
_id: ObjectId;
name: string;
slug: string;
members: OrganizationMember[];
settings: OrganizationSettings;
subscription: Subscription;
createdAt: Date;
}
// Application (groups forms + workflows)
interface Application {
_id: ObjectId;
organizationId: ObjectId;
projectId: ObjectId;
name: string;
slug: string;
description?: string;
icon?: string;
color?: string;
forms: ObjectId[];
workflows: ObjectId[];
releases: Release[];
createdAt: Date;
}
// Form
interface Form {
_id: ObjectId;
organizationId: ObjectId;
applicationId?: ObjectId;
name: string;
slug: string;
fields: FieldConfig[];
settings: FormSettings;
conditionalLogic?: ConditionalRule[];
computedFields?: ComputedFieldConfig[];
theme?: FormTheme;
createdAt: Date;
}
// Workflow
interface Workflow {
_id: ObjectId;
organizationId: ObjectId;
applicationId?: ObjectId;
name: string;
nodes: WorkflowNode[];
edges: WorkflowEdge[];
trigger: TriggerConfig;
status: 'draft' | 'active' | 'paused';
createdAt: Date;
}
Field Configurationβ
interface FieldConfig {
type: FieldType; // 30+ types
path: string; // Unique identifier
label: string;
required?: boolean;
placeholder?: string;
helpText?: string;
defaultValue?: any;
width?: 'full' | 'half' | 'third' | 'quarter';
validation?: ValidationRules;
options?: SelectOption[]; // For dropdowns, radios, etc.
// Type-specific properties...
}
type FieldType =
| 'short_text' | 'long_text' | 'email' | 'phone' | 'number' | 'currency' | 'url'
| 'dropdown' | 'multi_select' | 'radio' | 'checkbox' | 'toggle'
| 'date' | 'time' | 'datetime'
| 'rating' | 'slider' | 'scale' | 'ranking' | 'matrix'
| 'file_upload' | 'signature' | 'color'
| 'address'
| 'section' | 'divider' | 'heading' | 'html' | 'hidden'
| 'computed';
NPM Packagesβ
Current Packagesβ
| Package | Status | Description |
|---|---|---|
@netpad/templates | Active | 100+ form/workflow templates |
@netpad/mcp-server | Active | MCP tools for AI assistants |
@netpad/cli | Active | Command-line interface |
Future Packagesβ
| Package | Status | Description |
|---|---|---|
@netpad/workflow-renderer | Planned | Read-only workflow visualization |
@netpad/forms | Future | Form rendering SDK |
@netpad/workflows | Future | Workflow execution SDK |
Package Architectureβ
packages/
βββ templates/
β βββ src/
β β βββ forms/ # Form templates by category
β β βββ workflows/ # Workflow templates
β β βββ index.ts # Exports
β βββ package.json
β
βββ mcp-server/
β βββ src/
β β βββ tools/ # MCP tool implementations
β β βββ resources/ # Resource handlers
β β βββ index.ts
β βββ package.json
β
βββ cli/
βββ src/
β βββ commands/ # CLI commands
β βββ index.ts
βββ package.json
MCP Server (AI Integration)β
The MCP server allows AI assistants (Claude, Cursor) to:
- Generate forms from natural language descriptions
- Create workflows programmatically
- Browse and use templates
- Validate configurations
Available Toolsβ
| Tool | Description |
|---|---|
generate_form | Create form config from description |
generate_field | Create single field config |
generate_conditional_logic | Create conditional rules |
generate_computed_field | Create computed field formulas |
browse_templates | Search and list templates |
get_reference | Get field types, operators, etc. |
validate_form_config | Validate configuration |
Usage Exampleβ
User: "Create a patient intake form with name, DOB, allergies, and current medications"
AI (via MCP): Calls generate_form tool with description
β Returns complete FormConfig with appropriate field types
Development Patternsβ
Adding a New Field Typeβ
- Add type to
FieldTypeunion insrc/types/form.ts - Create renderer in
src/components/FormBuilder/Fields/ - Add validation logic in
src/lib/platform/validation.ts - Add to field palette in
src/components/FormBuilder/FieldPalette/ - Update MCP server field type reference
Adding a New Workflow Nodeβ
- Add type to
NodeTypeunion insrc/types/workflow.ts - Create node component in
src/components/WorkflowEditor/Nodes/ - Implement execution logic in
src/lib/platform/nodes/ - Add to node palette
- Update MCP server node reference
Adding a New API Endpointβ
- Create route file in appropriate
src/app/api/directory - Use existing auth/org middleware patterns
- Add TypeScript types for request/response
- Document in API reference
Environment Variablesβ
Requiredβ
# MongoDB
MONGODB_URI=mongodb+srv://...
MONGODB_DATABASE=netpad
# Auth
NEXTAUTH_SECRET=...
NEXTAUTH_URL=http://localhost:3000
AI Providers (at least one required)β
# Ollama (local, highest priority)
OLLAMA_BASE_URL=http://localhost:11434
# OpenAI
OPENAI_API_KEY=sk-...
# OpenRouter (fallback)
OPENROUTER_API_KEY=sk-or-...
Optionalβ
# Storage
BLOB_STORAGE_URL=...
# Email
SMTP_HOST=...
SMTP_PORT=...
# Integrations
SLACK_WEBHOOK_URL=...
Testingβ
Backend Testsβ
# Run all backend tests
npm run test
# Run specific test file
npm run test -- forms.test.ts
# Current status: 25/25 tests passing
E2E Testsβ
# Run Playwright tests
npm run test:e2e
# 22 test cases across 7 user journeys
Manual QAβ
Structured test cases exist for:
- Form builder functionality
- Workflow editor functionality
- Conversational forms
- Template operations
- Application export/import
Performance Considerationsβ
MongoDB Indexesβ
Key indexes for common queries:
// Forms
{ organizationId: 1 }
{ organizationId: 1, applicationId: 1 }
{ slug: 1 }
// Submissions
{ formId: 1, createdAt: -1 }
// Workflows
{ organizationId: 1 }
{ trigger.type: 1 }
Cachingβ
- React Query for client-side caching
- API route caching for template data
- Vector embeddings cached in Atlas
Bundle Sizeβ
- Tree-shaking enabled
- Dynamic imports for heavy components (ReactFlow)
- Route-based code splitting
Securityβ
Data Protectionβ
- Connection vault uses AES-256-GCM encryption
- Credentials never logged or exposed in responses
- Organization-scoped data isolation
Authenticationβ
- Session-based auth with secure cookies
- CSRF protection
- Rate limiting on API endpoints
Input Validationβ
- Server-side validation on all inputs
- MongoDB query sanitization
- File upload type/size restrictions
Next Stepsβ
- Review Getting Started for setup instructions
- Explore the codebase with this architecture in mind
- Pick an area that interests you
- Ask questionsβthe codebase is large but navigable
Architecture questions? Open a GitHub discussion.