Skip to content

AnoushkaSamanta/codekraft

Repository files navigation

CodeKraft

Project Overview

CodeKraft is an AI-powered web application builder that allows users to create fully functional Next.js applications through natural language conversations. It leverages advanced AI agents to interpret user requirements, write production-quality code, manage dependencies, and deploy applications in isolated sandbox environments.

What Problem Does It Solve?

Traditional web development requires extensive knowledge of frameworks, libraries, design patterns, and deployment processes. CodeKraft democratizes web development by:

  • Eliminating the learning curve for non-technical users
  • Accelerating development time for experienced developers
  • Providing instant prototyping capabilities
  • Generating production-ready code following best practices

Why This Project Exists

This project bridges the gap between idea and implementation, enabling:

  • Rapid MVP development for startups and entrepreneurs
  • Learning tool for students and aspiring developers
  • Productivity enhancement for professional developers
  • Low-code/no-code solution for business users

Features

Core Functional Features

  • AI-Powered Code Generation: Natural language to production-ready Next.js applications
  • Interactive Chat Interface: Conversational project creation and modification
  • Real-time Code Execution: Isolated sandbox environments using E2B technology
  • Multi-Agent System: Specialized AI agents for different development tasks
  • Project Management: Create, store, and manage multiple projects
  • Message History: Complete conversation and code generation history per project
  • Code Fragment Management: Track and version code changes
  • Automatic Dependency Management: AI installs required npm packages automatically
  • Shadcn UI Integration: Pre-installed, production-ready UI components
  • Authentication & Authorization: Secure user authentication via Clerk
  • Usage Tracking & Rate Limiting: Fair usage policies with credit-based system

Non-Functional Features

  • Performance: Fast response times with efficient database queries
  • 🔒 Security: User isolation, secure authentication, and rate limiting
  • 📈 Scalability: Event-driven architecture using Inngest for background jobs
  • 🎨 Modern UI/UX: Responsive design with dark mode support
  • 🛡️ Type Safety: Full TypeScript implementation
  • 🔄 Real-time Updates: Hot reload in sandbox environments
  • 📱 Responsive Design: Mobile-friendly interface
  • Accessibility: ARIA-compliant UI components

Tech Stack

Frontend Technologies

  • Next.js 16.1.1 - React framework for production-grade applications
    • Why? Server-side rendering, routing, and API routes in one framework
  • React 19.2.3 - UI library
    • Why? Component-based architecture and virtual DOM for optimal performance
  • TypeScript 5 - Type-safe JavaScript
    • Why? Enhanced developer experience and reduced runtime errors
  • Tailwind CSS 4 - Utility-first CSS framework
    • Why? Rapid styling without writing custom CSS
  • Shadcn UI - Pre-built accessible components
    • Why? Production-ready, customizable components built on Radix UI
  • Radix UI - Unstyled accessible components
    • Why? Accessibility-first primitives
  • Lucide React - Icon library
    • Why? Modern, consistent icon set

Backend Technologies

  • Next.js API Routes - Server-side API endpoints
    • Why? Unified frontend and backend in a single framework
  • Prisma 7.2.0 - Type-safe ORM
    • Why? Type-safe database queries and automatic migrations
  • PostgreSQL - Relational database
    • Why? Robust, ACID-compliant, and widely supported
  • Inngest 3.49.1 - Event-driven workflow engine
    • Why? Durable background job execution and multi-agent orchestration
  • @inngest/agent-kit - AI agent framework
    • Why? Structured multi-agent systems with tool calling

AI & Code Execution

  • Google Gemini 2.5 Flash - Large language model
    • Why? Fast, cost-effective, and capable of complex reasoning
  • E2B Code Interpreter - Isolated code execution sandboxes
    • Why? Secure, containerized environments for running user-generated code

Authentication & Security

  • Clerk - Authentication platform
    • Why? Complete auth solution with social logins and user management
  • rate-limiter-flexible - Rate limiting
    • Why? Prevent abuse with flexible, Prisma-integrated rate limiting

Development Tools

  • ESLint - Code linting
  • Docker & Docker Compose - Containerization
  • Zod - Schema validation
  • React Hook Form - Form management
  • TanStack Query - Server state management

System Architecture / Design

High-Level Architecture

┌─────────────────────────────────────────────────────────────────┐
│                         User Interface                          │
│                    (Next.js App Router)                         │
└────────────────┬───────────────────────────────┬────────────────┘
                 │                               │
                 ▼                               ▼
┌────────────────────────────┐   ┌──────────────────────────────┐
│     Authentication         │   │    API Routes                │
│       (Clerk)              │   │  (Server Actions)            │
└────────────────────────────┘   └─────────────┬────────────────┘
                                                │
                                                ▼
                ┌───────────────────────────────────────────────┐
                │           Database (PostgreSQL)               │
                │   ┌──────────┬──────────┬──────────┬────────┐│
                │   │  Users   │ Projects │ Messages │ Usage  ││
                │   └──────────┴──────────┴──────────┴────────┘│
                └───────────────────┬───────────────────────────┘
                                    │
                                    ▼
                ┌─────────────────────────────────────────────┐
                │      Inngest Event System                   │
                │   (Background Job Orchestration)            │
                └──────────────────┬──────────────────────────┘
                                   │
                                   ▼
        ┌──────────────────────────────────────────────────────┐
        │            Multi-Agent AI System                     │
        │  ┌────────────────────────────────────────────────┐ │
        │  │  Code Agent (Gemini 2.5 Flash)                 │ │
        │  │  ┌────────────┬────────────┬─────────────┐    │ │
        │  │  │  Terminal  │   Files    │  ReadFiles  │    │ │
        │  │  │    Tool    │    Tool    │    Tool     │    │ │
        │  │  └────────────┴────────────┴─────────────┘    │ │
        │  └────────────────────┬───────────────────────────┘ │
        └───────────────────────┼─────────────────────────────┘
                                │
                                ▼
                ┌───────────────────────────────────┐
                │    E2B Sandbox Environment       │
                │  (Isolated Next.js Container)    │
                │  ┌────────────────────────────┐  │
                │  │ Next.js App with Hot Reload│  │
                │  │ Shadcn UI Components       │  │
                │  │ Auto-installed Dependencies│  │
                │  └────────────────────────────┘  │
                └───────────────────────────────────┘

Design Patterns Used

  1. Multi-Agent Pattern: Separate agents handle different aspects of code generation
  2. Event-Driven Architecture: Inngest manages asynchronous workflows
  3. Repository Pattern: Prisma acts as a data access layer
  4. Server Actions: Next.js server actions for secure server-side operations
  5. Tool Pattern: AI agents use tools (terminal, file operations) to interact with sandbox
  6. Credit-Based Rate Limiting: Fair usage enforcement with token bucket algorithm

Module Separation & Responsibilities

Module Responsibility
app/(root) Landing page, authentication, pricing
app/projects/[projectId] Project workspace and chat interface
app/api/inngest Inngest webhook endpoint
modules/auth Authentication actions and utilities
modules/home Project creation and listing
modules/projects Project CRUD operations
modules/messages Message handling and streaming
inngest/ AI agent definitions and event handlers
lib/ Database connection, utilities, usage tracking
components/ Reusable UI components
generated/prisma Generated Prisma client

Project Workflow

User Journey: Creating an Application

1. User Input
   ↓
   User describes application: "Create a todo app with dark mode"
   ↓
2. Request Processing
   ↓
   Server action creates project and user message in database
   ↓
3. Event Trigger
   ↓
   Inngest event "code-agent/run" is sent
   ↓
4. Sandbox Creation
   ↓
   E2B creates isolated Next.js sandbox environment
   ↓
5. Message History Retrieval
   ↓
   Load all previous messages for context
   ↓
6. AI Agent Activation
   ↓
   Gemini AI agent receives system prompt and user request
   ↓
7. Code Generation
   ↓
   Agent plans implementation and uses tools:
   - terminal: Install dependencies (npm install)
   - createOrUpdateFiles: Write/update code files
   - readFiles: Read existing code
   ↓
8. Execution
   ↓
   Code runs in sandbox with hot reload
   ↓
9. Response Generation
   ↓
   Agent generates summary of what was built
   ↓
10. Database Update
    ↓
    Save assistant message and code fragments
    ↓
11. User Notification
    ↓
    Response streamed back to user interface
    ↓
12. Preview Available
    ↓
    User can view live application in sandbox URL

Data Flow

User Message → Database → Inngest → AI Agent → Tools → Sandbox → Response → Database → UI

Important Business Logic

  1. Credit System:

    • Free users: 5 credits per 30 days
    • Pro users: 100 credits per 30 days
    • Each generation costs 1 credit
  2. Sandbox Management:

    • Each project gets a persistent sandbox ID
    • Sandboxes are pre-configured with Next.js 16.1.1 and Shadcn UI
  3. Message Types:

    • USER: Messages from users
    • ASSISTANT: AI-generated responses
    • Result types: RESULT (success), ERROR (failure)
  4. Code Fragment Tracking:

    • Each assistant message can have an associated fragment
    • Fragments contain: sandbox URL, title, and file changes (JSON)

Folder / Directory Structure

v0/
├── prisma/                           # Database schema and migrations
│   ├── schema.prisma                 # Prisma schema definition
│   └── migrations/                   # Database migration history
├── public/                           # Static assets (logo, images)
├── sandbox-templates/                # E2B sandbox configuration
│   └── next-js/
│       ├── e2b.Dockerfile           # Custom sandbox Docker image
│       ├── e2b.toml                 # E2B configuration
│       └── compile_page.sh          # Build script
├── src/
│   ├── app/                         # Next.js App Router
│   │   ├── (root)/                  # Public routes
│   │   │   ├── page.tsx            # Landing page
│   │   │   ├── pricing/            # Pricing page
│   │   │   ├── sign-in/            # Sign-in page
│   │   │   └── sign-up/            # Sign-up page
│   │   ├── api/                     # API routes
│   │   │   └── inngest/            # Inngest webhook endpoint
│   │   ├── projects/
│   │   │   └── [projectId]/        # Dynamic project workspace
│   │   ├── globals.css             # Global styles
│   │   └── layout.tsx              # Root layout
│   ├── components/                  # Reusable UI components
│   │   ├── ui/                     # Shadcn UI components
│   │   ├── ai-elements/            # AI-specific components
│   │   ├── query-provider.tsx      # TanStack Query provider
│   │   └── theme-provider.tsx      # Dark mode provider
│   ├── generated/                   # Auto-generated code
│   │   └── prisma/                 # Generated Prisma client
│   ├── hooks/                       # Custom React hooks
│   ├── inngest/                     # Inngest functions and client
│   │   ├── client.ts               # Inngest client setup
│   │   ├── functions.ts            # AI agent function definitions
│   │   └── utils.ts                # Helper utilities
│   ├── lib/                         # Core utilities
│   │   ├── db.ts                   # Prisma database client
│   │   ├── usage.ts                # Rate limiting and credit system
│   │   └── utils.ts                # General utilities (cn, etc.)
│   ├── modules/                     # Feature modules
│   │   ├── auth/                   # Authentication logic
│   │   ├── home/                   # Home page components
│   │   ├── messages/               # Message handling
│   │   ├── projects/               # Project CRUD operations
│   │   └── usage/                  # Usage tracking UI
│   ├── prompt.ts                    # AI system prompts
│   └── proxy.ts                     # Proxy configuration
├── components.json                  # Shadcn UI configuration
├── docker-compose.yml              # PostgreSQL container setup
├── eslint.config.mjs               # ESLint configuration
├── next.config.ts                  # Next.js configuration
├── package.json                    # Dependencies and scripts
├── postcss.config.mjs              # PostCSS configuration
├── prisma.config.ts                # Prisma configuration
├── tsconfig.json                   # TypeScript configuration
└── README.md                       # Project documentation

Installation & Setup

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v20 or higher) - Download
  • npm (comes with Node.js) or pnpm
  • Docker and Docker Compose - Download
  • PostgreSQL (or use Docker)
  • Git - Download

Step-by-Step Installation

1. Clone the Repository

git clone https://github.com/yourusername/codekraft.git
cd codekraft

2. Install Dependencies

npm install
# or
pnpm install
# or
yarn install

3. Environment Setup

Create a .env file in the root directory:

# Database
DATABASE_URL="postgresql://postgres:postgres@localhost:5431/postgres"

# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key
CLERK_SECRET_KEY=your_clerk_secret_key
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up

# Inngest
INNGEST_EVENT_KEY=your_inngest_event_key
INNGEST_SIGNING_KEY=your_inngest_signing_key

# E2B
E2B_API_KEY=your_e2b_api_key

# Google AI
GOOGLE_AI_API_KEY=your_google_ai_api_key

# App Configuration
NEXT_PUBLIC_APP_URL=http://localhost:3000

4. Start PostgreSQL Database

docker compose up -d

This starts a PostgreSQL database on port 5431.

5. Run Database Migrations

npx prisma migrate dev

6. Generate Prisma Client

npx prisma generate

7. (Optional) Seed the Database

npx prisma db seed

8. Run the Development Server

npm run dev

The application will be available at http://localhost:3000


Usage

Creating Your First Project

  1. Sign Up / Sign In

  2. Create a New Project

    • On the home page, enter a description of what you want to build
    • Example: "Create a landing page with a hero section, features, and contact form"
    • Click "Create Project" or press Enter
  3. View Progress

    • You'll be redirected to the project workspace
    • Watch as the AI agent generates code in real-time
    • Messages appear in the chat interface
  4. Interact with Your Application

    • Once generation completes, click "Open Preview" to view the live application
    • The app runs in an isolated sandbox environment
  5. Modify Your Project

    • Continue the conversation: "Add dark mode toggle" or "Change the color scheme to blue"
    • The AI agent will update your code incrementally

Important Configuration Files

  • Defines database models: User, Project, Message, Fragment, Usage
  • Customize data models here if needed
  • Contains AI agent system prompts
  • Modify to change agent behavior and coding standards
  • Defines the sandbox environment
  • Pre-installs Next.js 16.1.1 and Shadcn UI components
  • Next.js configuration
  • Modify for custom domains, redirects, etc.

Modifying Usage Limits

Edit src/lib/usage.ts:

export const FREE_POINTS = 5;      // Free tier credits
export const PRO_POINTS = 100;     // Pro tier credits
export const DURATION = 30 * 24 * 60 * 60; // Reset period (seconds)
export const GENERATION_COST = 1;  // Cost per generation

Security Considerations

Authentication & Authorization

  • Clerk handles all authentication flows
  • JWT-based session management
  • Protected API routes verify authentication using auth() from Clerk
  • User isolation: Users can only access their own projects

Data Protection

  • Database: User data stored in PostgreSQL with proper foreign key constraints
  • Cascade Deletes: Deleting a user removes all their projects and messages
  • Rate Limiting: Prevents abuse with credit-based system
  • Secure Environment Variables: Sensitive keys stored in .env (not committed to git)

Sandbox Security

  • E2B Sandboxes: Isolated containerized environments
  • No direct access to host system
  • Sandboxes are ephemeral and can be destroyed

Best Practices Followed

  • ✅ Server-side validation with Zod schemas
  • ✅ TypeScript for type safety
  • ✅ SQL injection prevention (Prisma ORM)
  • ✅ CORS configured properly
  • ✅ Rate limiting on expensive operations
  • ✅ No sensitive data logged

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages