Skip to content

About

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

49 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Build Component — AI-Powered React Component Studio

License: ISC Node.js React Express MongoDB Gemini AI

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.


Table of Contents


Overview

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.


Key Features

  • 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 .jsx file 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.

System Architecture

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
Loading

Component Generation Flow

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
Loading

Tech Stack

Frontend

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

Backend

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

Project Structure

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

Database Schema

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
    }
Loading

Models Summary

  1. User (src/models/user.model.js):
    • Stores account credentials with unique email validation and bcrypt-hashed passwords.
  2. ChatSession (src/models/chatsession.model.js):
    • Tracks individual conversation threads tied to a user. Titles are auto-generated from initial prompts.
  3. Message (src/models/message.model.js):
    • Stores conversational turns. Assistant turns include the raw JSX component string and structured feature bullet points.

REST API Reference

All protected endpoints require an authenticated JWT token transmitted via the token HTTP-only cookie or as a Bearer token in the Authorization header.

1. Authentication (/api/auth)

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

POST /api/auth/register

  • Request Body:
    {
      "name": "Jane Doe",
      "email": "jane@example.com",
      "password": "SecurePassword123"
    }
  • Response (201 Created):
    {
      "message": "User registered successfully"
    }

POST /api/auth/login

  • Request Body:
    {
      "email": "jane@example.com",
      "password": "SecurePassword123"
    }
  • Response (200 OK):
    {
      "message": "Login successful",
      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
    }

2. Chat Sessions (/api/chats)

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

POST /api/chats

  • Request Body:
    {
      "message": "Create a modern dark-mode pricing table with 3 tiers and monthly/annual toggle"
    }
  • Response (201 Created):
    {
      "newChatId": "651a2b3c4d5e6f7a8b9c0d1e"
    }

3. Messages (/api/message)

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

POST /api/message

  • 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"
      }
    }

4. User Profile (/api/user)

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

AI Pipeline & Prompt Engineering

The AI generation service resides in backend/src/services/ai.services.js.

Pipeline Steps:

  1. Rate Limiting: Enforces a minimum 1000ms pause between consecutive outbound AI calls to prevent burst limits.
  2. Model Selection: Uses Google's gemini-2.5-flash model via @google/generative-ai.
  3. 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"
      }
  4. Sanitization: Filters Markdown fences (json ... ) and cleans control characters before parsing into native JavaScript objects.

Getting Started

Prerequisites


1. Backend Setup

  1. Open a terminal and navigate to the backend directory:

    cd backend
  2. Install dependencies:

    npm install
  3. Create the .env file from the provided template:

    cp .env.example .env
  4. Populate .env with 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
  5. Start the backend development server:

    npm run dev

    The backend server will run at http://localhost:3000.


2. Frontend Setup

  1. In a separate terminal, navigate to the frontend directory:

    cd frontend
  2. Install dependencies:

    npm install
  3. Start the React development server:

    npm start

    The application will automatically open at http://localhost:3000 (or http://localhost:3001 if 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.


Environment Variables

Backend (backend/.env)

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...

Deployment

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

Deployment Configuration Checklist:

  • CORS Configuration: backend/index.js sets origin to https://build-component.vercel.app with credentials: true.
  • Cookie Security: Auth cookies are configured with secure: true, sameSite: "none", and httpOnly: true for cross-site cross-domain communication between Vercel and Render.
  • Environment Variables: Configure MONGO_URI, JWT_SECRET, and GEMINI_API_KEY in Render's dashboard.

License

This project is licensed under the ISC License.

About

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages