Chaos Coder is a Next.js application that generates multiple variations of web applications simultaneously using AI. This tool helps developers quickly explore different implementation possibilities for their web application ideas.
Note: All the code for this project is located in the nextjs-web-app
folder.
This project contains several important files that form the core functionality:
-
nextjs-web-app/src/app/results/page.tsx
(32KB): The main results page component that displays the generated web application variations. Handles code generation, UI rendering, voice input processing, and performance metrics tracking. -
nextjs-web-app/src/app/dashboard/page.tsx
(24KB): The user dashboard component. Manages user authentication state, subscription information, credit tracking, and user profile data. -
nextjs-web-app/src/app/page.tsx
(20KB): The landing page component with the primary application interface.
-
nextjs-web-app/src/lib/payment/index.ts
(24KB): The centralized payment service. Handles all Stripe integration, subscription management, customer creation, checkout sessions, webhook processing, and billing operations. -
nextjs-web-app/db/schema-updates.sql
(20KB): Database schema definitions for the Supabase backend. Contains table structures, indexes, row-level security policies, and stored procedures for user authentication, credit management, and subscription tracking.
nextjs-web-app/src/components/SubscriptionPlans.tsx
(16KB): Component for displaying and managing subscription tiers and plans.
nextjs-web-app/src/context/AuthContext.tsx
: Centralized authentication context that manages user sessions, tokens, and authentication state.nextjs-web-app/src/context/ThemeContext.tsx
: Theme management context for light/dark mode.nextjs-web-app/src/context/GenerationsContext.tsx
: Context for managing the number of web application variations to generate. Provides consistent state across the application.
nextjs-web-app/public/favicon.ico
(124KB): The website favicon.nextjs-web-app/public/coin.png
(100KB): Image asset for the credit/token system.
The purpose of Chaos Coder is to accelerate the development process by providing multiple variations of code solutions for web applications. By generating multiple different approaches at once, developers can compare and choose the best implementation for their specific needs.
- Generates multiple unique web application variations (configurable with no upper limit)
- Real-time code preview for each variation
- Interactive interface with theme toggling (light/dark mode)
- Voice input support for hands-free prompting
- Performance metrics for generation times
- Keyboard shortcuts for quick access to tools
- Robust user authentication with centralized AuthService
- Secure payment processing with Stripe integration
- Subscription plans (Free, Pro, Ultra) with different credit allotments
- Credit purchase system for additional generations
- User profile management with first name personalization
- Responsive design for mobile and desktop
- Persistent settings via localStorage
- Next.js 15 with Turbopack
- TypeScript
- Tailwind CSS
- Framer Motion
- Supabase for authentication and database
- Stripe for payment processing
- Zod for schema validation
- Hugging Face Inference API
- Radix UI for accessible components
- Node.js 18.x or higher
- npm or yarn
- A Supabase account for authentication and database
- A Stripe account for payment processing
- A Hugging Face account for AI model access
git clone https://github.com/aj47/chaos-coder.git
cd chaos-coder
cd nextjs-web-app
npm install
Create a .env
file in the nextjs-web-app
directory with the following variables:
# Hugging Face API token
HF_API_TOKEN=your_huggingface_api_token
# Supabase configuration
NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key
# Stripe configuration
STRIPE_SECRET_KEY=your_stripe_secret_key
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=your_stripe_webhook_secret
STRIPE_PRO_PRICE_ID=your_stripe_pro_price_id
STRIPE_ULTRA_PRICE_ID=your_stripe_ultra_price_id
# Site URL
NEXT_PUBLIC_SITE_URL=http://localhost:3000
# Optional: Portkey API key if using Portkey
PORTKEY_API_KEY=your_portkey_api_key
- Create a new project in Supabase
- Enable Email Auth in Authentication settings
- Set up email templates for verification
- Create necessary database tables by running the schema scripts:
# First create the exec_sql function psql -h your_supabase_host -U postgres -d postgres -f db/create-exec-sql-function.sql # Then apply the schema updates npm run db:schema
- Copy your project URL and anon key to the
.env
file
- Create a Stripe account if you don't have one
- Set up subscription products for Pro and Ultra tiers
- Configure webhook endpoints in the Stripe dashboard
- Add your Stripe keys to the
.env
file
npm run dev
The application will be available at http://localhost:3000 (or another port if 3000 is in use).
- Access the application in your web browser
- Sign up for an account or log in if you already have one
- View your available credits in the dashboard
- Upgrade to a paid subscription or purchase additional credits
- Enter your web application requirements or ideas in the input form
- View and compare the five different application variations
- Use the code preview panel to inspect and edit the generated code
- Deploy your favorite variation directly from the interface
- Shift+L: Open prompt input
- Shift+P: Open performance metrics
- Shift+T: Toggle theme (light/dark mode)
# Start development server with Turbopack
npm run dev
# Build for production
npm run build
# Start production server
npm start
# Run linting
npm run lint
# Apply database schema updates
npm run db:schema
# Deploy (requires configuration)
npm run deploy
nextjs-web-app/
├── db/ # Database scripts and schemas
├── public/ # Static assets
├── scripts/ # Utility scripts
├── src/
│ ├── app/ # Next.js app router pages
│ │ ├── api/ # API routes
│ │ │ ├── stripe/ # Payment API endpoints
│ │ │ └── ... # Other API endpoints
│ │ ├── auth/ # Auth-related pages
│ │ └── ... # Other pages
│ ├── components/ # Reusable UI components
│ │ ├── auth/ # Authentication components
│ │ └── ... # Other components
│ ├── context/ # React context providers
│ │ ├── auth/ # Authentication context
│ │ ├── theme/ # Theme management context
│ │ └── generations/ # Generations context
│ ├── lib/ # Utility functions and services
│ │ ├── auth/ # Centralized authentication service
│ │ ├── payment/ # Payment processing service
│ │ └── ... # Other utilities
│ ├── store/ # State management (Zustand)
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ └── fonts/ # Custom fonts
├── .env # Environment variables
├── .eslintrc.json # ESLint configuration
└── package.json # Project dependencies and scripts
The authentication system has been completely overhauled to use a centralized service-oriented architecture:
The AuthService
class in src/lib/auth/index.ts
provides a comprehensive API for all authentication operations:
// Client-side authentication
const { data, error } = await AuthService.signIn(email, password);
const { data, error } = await AuthService.signUp(email, password, firstName);
const { error } = await AuthService.signOut();
const { data, error } = await AuthService.signInWithOAuth('google');
// Server-side authentication
const supabase = await AuthService.createServerClient(cookieStore);
const { user, error } = await AuthService.getCurrentUser(supabase);
- Unified client and server authentication
- Consistent error handling
- Session management
- OAuth integration (Google)
- User metadata management
- Type-safe database operations
The payment system uses Stripe for processing subscriptions and one-time purchases:
The PaymentService
class in src/lib/payment/index.ts
handles all payment operations:
// Create checkout sessions
const { url } = await PaymentService.createSubscriptionCheckout(customerId, 'pro', userId);
const { url } = await PaymentService.createCreditPurchaseCheckout(customerId, amount, 'pro', userId);
// Handle webhook events
const { success, message } = await PaymentService.handleWebhookEvent(body, signature, webhookSecret);
// Manage subscriptions
const { success, message } = await PaymentService.cancelSubscription(userId);
- Subscription management (Free, Pro, Ultra tiers)
- One-time credit purchases
- Automatic credit allocation
- Stripe webhook integration
- Secure payment processing
- Comprehensive error handling
- Transaction history
The application uses a Supabase PostgreSQL database with the following tables:
-
profiles
- Purpose: Stores user profile information with subscription and credit data
- Schema:
id
(UUID): Primary key, linked to auth.userscredits
(INTEGER): Current credit balance for usermax_monthly_credits
(INTEGER): Monthly credit limit based on subscription tierstripe_customer_id
(TEXT): Stripe customer referencestripe_subscription_id
(TEXT): Stripe subscription referencesubscription_period_start
(TIMESTAMP): Start of current subscription periodsubscription_period_end
(TIMESTAMP): End of current subscription periodlast_credited_at
(TIMESTAMP): When credits were last refreshedsubscription_tier
(ENUM): 'free', 'pro', or 'ultra'subscription_status
(ENUM): Status from Stripe (active, past_due, etc.)updated_at
(TIMESTAMP): Last update timestamp
-
subscription_history
- Purpose: Tracks changes to user subscriptions
- Schema:
id
(UUID): Primary keyuser_id
(UUID): Reference to auth.userssubscription_tier
(TEXT): Tier of subscriptionstatus
(TEXT): Status of subscriptionamount_paid
(DECIMAL): Amount paidcurrency
(TEXT): Currency of paymentstripe_subscription_id
(TEXT): Stripe subscription referencestripe_customer_id
(TEXT): Stripe customer referencedescription
(TEXT): Additional detailscreated_at
(TIMESTAMP): When record was created
-
credit_purchases
- Purpose: Records one-time credit purchases
- Schema:
id
(UUID): Primary keyuser_id
(UUID): Reference to auth.usersamount
(INTEGER): Number of credits purchasedcost
(DECIMAL): Amount paidcurrency
(TEXT): Currency of paymentstripe_session_id
(TEXT): Stripe checkout session IDstripe_payment_intent_id
(TEXT): Stripe payment intent IDcreated_at
(TIMESTAMP): When purchase was made
-
credit_history
- Purpose: Audit trail of all credit transactions
- Schema:
id
(UUID): Primary keyuser_id
(UUID): Reference to auth.usersamount
(INTEGER): Number of credits added/removedtype
(TEXT): Transaction type (purchase, usage, reset, etc.)description
(TEXT): Additional detailscreated_at
(TIMESTAMP): When transaction occurred
-
credit_reset_logs
- Purpose: Logs when the credit reset function runs
- Schema:
id
(UUID): Primary keyexecuted_at
(TIMESTAMP): When reset was executedsuccess
(BOOLEAN): Whether reset was successfulerror_message
(TEXT): Any error details if failed
The database includes the following secure functions for managing credits:
add_user_credits
: Safely add credits to a userdeduct_user_credits
: Safely remove credits from a userreset_daily_credits
: Automatically refresh credits dailyhandle_new_user
: Creates a profile when a new user signs up
When a new user signs up, a trigger automatically creates a profile record for them with default subscription values (free tier, 30 credits).
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Join our Discord community for support, discussions, and updates: