Build Component is a full-stack, AI-assisted development workspace that translates natural language prompts into production-grade React components with live in-browser execution, code syntax highlighting, explanation breakdown, and chat session persistence.
- Overview
- Key Features
- System Architecture
- Tech Stack
- Project Structure
- Database Schema
- REST API Reference
- AI Pipeline & Prompt Engineering
- Getting Started
- Environment Variables
- Deployment
- License
Developers and designers frequently spend time creating boilerplate UI components from scratch. Build Component bridges prompt-to-code workflows by integrating Google Gemini Generative AI with a live Sandpack virtual execution container in the browser. Users can prompt for any component (e.g., responsive pricing card, dashboard widget, animated modal), inspect the clean JSX code, run and interact with the rendered component immediately, and iteratively refine it in conversation threads.
- Prompt-to-Component Generation: Converts natural language prompts into clean, self-contained React/JSX code with structural explanations.
- Live In-Browser Sandpack Sandbox: Instant rendering with live preview using
@codesandbox/sandpack-react, allowing real-time interaction without local bundling. - Syntax Highlighting & Code Utilities: Code viewer with Prism oneDark styling, one-click clipboard copying, and direct
.jsxfile download. - Fullscreen Preview Mode: Expand any generated component into a full-viewport canvas for detailed testing and visual inspection.
- Persistent Chat Sessions: Conversational threads stored in MongoDB with full message history and iterative component refactoring.
- Secure Authentication: JWT-based session management delivered via secure, HTTP-only, SameSite cookies with password hashing (
bcryptjs). - Profile & Data Management: Self-service user profile updates and account deletion with complete cascade cleanup of chat sessions and messages.
- Throttling & Rate Limiting: Built-in backend rate-limiting mechanism preventing quota exhaustion against the Gemini API.
flowchart TD
subgraph Client["Frontend (React 19 SPA)"]
UI[User Interface]
SP[Sandpack Live Runtime]
SH[Syntax Highlighter]
AuthGuard[Client Auth Wrapper]
end
subgraph Server["Backend API (Express 5)"]
Router[API Route Handlers]
AuthMW[JWT Auth Middleware]
AISvc[AI Service Layer]
ChatSvc[Chat & Message Service]
UserSvc[User Service]
end
subgraph External["External Cloud Services"]
Gemini["Google Gemini 2.5 Flash API"]
MongoDB[(MongoDB Atlas)]
end
UI -->|HTTP Requests / Cookies| Router
Router --> AuthMW
AuthMW --> ChatSvc
AuthMW --> UserSvc
ChatSvc --> AISvc
AISvc -->|Rate-Limited Prompts| Gemini
ChatSvc --> MongoDB
UserSvc --> MongoDB
Router -->|JSON + Component JSX| UI
UI --> SP
UI --> SH
sequenceDiagram
autonumber
actor User as Developer / User
participant Client as Frontend (React)
participant API as Express Server
participant Gemini as Google Gemini AI
participant DB as MongoDB
User->>Client: Enters prompt ("Create an animated pricing card")
Client->>API: POST /api/chats or /api/message
API->>API: Validate JWT Auth Token
API->>DB: Persist user prompt message
API->>Gemini: Request component JSON (Code + 10-point explanation)
Gemini-->>API: Returns formatted JSON response
API->>API: Sanitize & parse Markdown JSON
API->>DB: Persist assistant message (JSX + explanations)
API-->>Client: Return generated component & explanation
Client->>Client: Render syntax-highlighted code
User->>Client: Clicks "Run"
Client->>Client: Mounts virtual Sandpack runtime & displays live component
| Technology | Purpose |
|---|---|
| React 19 | Core reactive user interface library |
| React Router v7 | Single Page Application (SPA) declarative client routing |
| @codesandbox/sandpack-react | Browser-based React compiler and runtime sandbox |
| @codesandbox/sandpack-themes | Dark theme presets (atomDark) for sandbox UI |
| react-syntax-highlighter | Prism JSX syntax highlighting (oneDark) |
| Vanilla CSS | Scoped styling with responsive mobile drawer controls |
| Technology | Purpose |
|---|---|
| Node.js | Server-side JavaScript runtime |
| Express 5 | RESTful web API framework |
| MongoDB & Mongoose 9 | NoSQL object document modeling and persistence |
| @google/generative-ai | SDK for Google Gemini 2.5 Flash model invocation |
| jsonwebtoken (JWT) | Stateless authentication token generation and verification |
| bcryptjs | Salted cryptographic password hashing |
| cookie-parser | HTTP cookie extraction for secure auth headers |
| cors | Cross-Origin Resource Sharing configuration |
| express-rate-limit | Request rate-limiting protection |
Build_Component/
├── README.md # Master project documentation
│
├── backend/ # Node.js + Express API server
│ ├── .env.example # Sample environment configuration
│ ├── .gitignore # Backend gitignore
│ ├── index.js # Server entry point & CORS configuration
│ ├── package.json # Backend dependencies and scripts
│ └── src/
│ ├── config/
│ │ └── db.js # Mongoose connection handler
│ ├── controllers/
│ │ ├── auth.controller.js # Auth request handlers
│ │ ├── chat.controller.js # Chat session endpoints
│ │ ├── message.controller.js # Message creation and retrieval
│ │ └── user.controller.js # Profile management handlers
│ ├── middleware/
│ │ └── auth.middleware.js # JWT verification & token generator
│ ├── models/
│ │ ├── chatsession.model.js # Chat session schema
│ │ ├── message.model.js # Message & Component code schema
│ │ └── user.model.js # User account schema
│ ├── routes/
│ │ ├── auth.routes.js # /api/auth routes
│ │ ├── chat.routes.js # /api/chats routes
│ │ ├── message.routes.js # /api/message routes
│ │ └── user.routes.js # /api/user routes
│ └── services/
│ ├── ai.services.js # Gemini API integration & JSON parsing
│ ├── auth.services.js # Register, login, cookie setting
│ ├── chat.services.js # Chat session business logic
│ ├── message.services.js # Message business logic
│ └── user.services.js # Profile update & cascade deletion
│
└── frontend/ # React 19 Client SPA
├── package.json # Frontend dependencies and scripts
├── public/ # Static HTML and assets
└── src/
├── App.js # Router setup & authentication wrapper
├── index.js # React DOM root entry
├── Pages/
│ ├── Chat.js # Main chat workspace & live preview
│ ├── Home.js # New chat launcher view
│ ├── Login.js # User login screen
│ ├── ProfilePage.js # User settings & account deletion
│ └── Register.js # User registration screen
├── components/
│ ├── ChatBox.js # Message list container
│ ├── ChatBox1.js # Initial chat input launcher
│ ├── ChatInput.js # Active session input bar
│ ├── ChatMessage.js # Code block, Sandpack runtime & actions
│ ├── Chatlistitem.js # Sidebar chat item with delete action
│ ├── LoadingSpinner.js # Async loading animation
│ └── Sidebar.js # Collapsible drawer with chat history
└── styles/ # CSS stylesheets
erDiagram
User ||--o{ ChatSession : "owns"
ChatSession ||--o{ Message : "contains"
User {
ObjectId _id PK
string name
string email UK
string password "hashed"
date createdAt
}
ChatSession {
ObjectId _id PK
ObjectId userId FK
string title
date createdAt
date updatedAt
}
Message {
ObjectId _id PK
ObjectId chatSessionId FK
string role "user | assistant"
string prompt "optional"
array explanation "bullet points"
object component "code: string"
date createdAt
}
- User (
src/models/user.model.js):- Stores account credentials with unique email validation and bcrypt-hashed passwords.
- ChatSession (
src/models/chatsession.model.js):- Tracks individual conversation threads tied to a user. Titles are auto-generated from initial prompts.
- Message (
src/models/message.model.js):- Stores conversational turns. Assistant turns include the raw JSX component string and structured feature bullet points.
All protected endpoints require an authenticated JWT token transmitted via the token HTTP-only cookie or as a Bearer token in the Authorization header.
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/api/auth/register |
No | Creates a new user account |
POST |
/api/auth/login |
No | Validates credentials and sets token cookie |
GET |
/api/auth/verify |
Yes | Checks if current session is authenticated |
POST |
/api/auth/logout |
Yes | Clears session cookie |
- Request Body:
{ "name": "Jane Doe", "email": "jane@example.com", "password": "SecurePassword123" } - Response (201 Created):
{ "message": "User registered successfully" }
- Request Body:
{ "email": "jane@example.com", "password": "SecurePassword123" } - Response (200 OK):
{ "message": "Login successful", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/api/chats |
Yes | Initializes a new chat session and generates first component |
GET |
/api/chats |
Yes | Lists all chat sessions for the logged-in user |
GET |
/api/chats/:chatId |
Yes | Retrieves metadata for a specific session |
DELETE |
/api/chats/:chatId |
Yes | Deletes session and cascades delete to all child messages |
- Request Body:
{ "message": "Create a modern dark-mode pricing table with 3 tiers and monthly/annual toggle" } - Response (201 Created):
{ "newChatId": "651a2b3c4d5e6f7a8b9c0d1e" }
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/api/message |
Yes | Sends follow-up prompt, triggers Gemini, saves & returns response |
GET |
/api/message/:chatId |
Yes | Fetches all messages belonging to a chat session |
- Request Body:
{ "chatId": "651a2b3c4d5e6f7a8b9c0d1e", "message": "Add an interactive tooltip explaining each feature on hover" } - Response (201 Created):
{ "newMessage": { "role": "user", "prompt": "Add an interactive tooltip...", "_id": "651a2b3c4d5e6f7a8b9c0d1f" }, "newAiMessage": { "role": "assistant", "explanation": [ "Added tooltip state to each tier", "Included pure CSS hover transitions" ], "component": { "code": "import React, { useState } from 'react';\n\nexport default function PricingTable() { ... }" }, "_id": "651a2b3c4d5e6f7a8b9c0d20" } }
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/api/user |
Yes | Returns authenticated user details (name, email) |
PUT |
/api/user |
Yes | Updates name, email, and optionally password |
DELETE |
/api/user |
Yes | Permanently removes user account and all chat history |
The AI generation service resides in backend/src/services/ai.services.js.
- Rate Limiting: Enforces a minimum 1000ms pause between consecutive outbound AI calls to prevent burst limits.
- Model Selection: Uses Google's
gemini-2.5-flashmodel via@google/generative-ai. - Structured Output Prompting:
- Instructs the model to output a single consolidated React component.
- Demands exactly 10 concise bullet points explaining key features.
- Constrains output to strict JSON with keys:
{ "explanation": ["string"], "code": "string" }
- Sanitization: Filters Markdown fences (
json ...) and cleans control characters before parsing into native JavaScript objects.
- Node.js (v18.0.0 or later recommended)
- npm (v9.0.0+)
- MongoDB Atlas cluster or local MongoDB instance
- Google AI Studio API Key (Gemini API)
-
Open a terminal and navigate to the backend directory:
cd backend -
Install dependencies:
npm install
-
Create the
.envfile from the provided template:cp .env.example .env
-
Populate
.envwith your actual credentials:PORT=3000 MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/build_component?retryWrites=true&w=majority JWT_SECRET=your_jwt_secret_key_here GEMINI_API_KEY=your_gemini_api_key_here
-
Start the backend development server:
npm run dev
The backend server will run at
http://localhost:3000.
-
In a separate terminal, navigate to the frontend directory:
cd frontend -
Install dependencies:
npm install
-
Start the React development server:
npm start
The application will automatically open at
http://localhost:3000(orhttp://localhost:3001if port 3000 is occupied by the backend).
Tip
For local development with both frontend and backend on localhost, ensure cors in backend/index.js includes http://localhost:3000 (or your client port) and backend API URLs in frontend point to http://localhost:3000.
| Variable | Required | Description | Example |
|---|---|---|---|
PORT |
No | Port on which Express server listens | 3000 |
MONGO_URI |
Yes | MongoDB connection string | mongodb+srv://user:pwd@cluster.mongodb.net/db |
JWT_SECRET |
Yes | Cryptographic secret for signing tokens | super_secret_jwt_random_key |
GEMINI_API_KEY |
Yes | Google Gemini Generative AI API key | AIzaSy... |
The application is architected for decoupled cloud hosting:
- Frontend: Deployed to Vercel at
https://build-component.vercel.app - Backend: Deployed to Render at
https://build-component.onrender.com - Database: Managed on MongoDB Atlas
- CORS Configuration:
backend/index.jssetsorigintohttps://build-component.vercel.appwithcredentials: true. - Cookie Security: Auth cookies are configured with
secure: true,sameSite: "none", andhttpOnly: truefor cross-site cross-domain communication between Vercel and Render. - Environment Variables: Configure
MONGO_URI,JWT_SECRET, andGEMINI_API_KEYin Render's dashboard.
This project is licensed under the ISC License.