# Architecture of the Awesome-GPT-Image-2 Repository: A Deep Dive into the React and Vercel Stack

> Explore the architecture of the awesome-gpt-image-2 repository. Discover its React presentation layer, Vercel Serverless Functions, and Supabase-backed infrastructure for AI image generation.

- Repository: [苍何/awesome-gpt-image-2](https://github.com/freestylefly/awesome-gpt-image-2)
- Tags: architecture
- Published: 2026-08-30

---

**The awesome-gpt-image-2 repository implements a three-layer serverless architecture consisting of a React presentation layer, Vercel Serverless Functions for backend services, and Supabase-backed infrastructure for authentication, billing, and GPT-Image-2 generation.**

The architecture of the awesome-gpt-image-2 repository follows a modern Jamstack pattern optimized for AI image generation workflows. This single-page application combines a Vite-powered React frontend with Node.js serverless functions, creating a seamless bridge between users and the CIYUAN GPT-Image-2 API while handling complex concerns like credit management and multi-provider payments.

## High-Level Design Overview

The codebase is organized into three distinct logical layers that separate concerns across the stack.

The **Presentation Layer** manages UI components, client-side routing, state handling, and internationalization through modules like [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx), [`src/community.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/community.jsx), and [`src/styles.css`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/styles.css).

The **Backend Services Layer** comprises serverless functions under the `api/` directory that handle authentication, profile management, credit systems, image generation, and administrative dashboards via the Vercel Functions convention.

The **Infrastructure Layer** includes build configuration ([`vite.config.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/vite.config.js)), deployment settings ([`vercel.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/vercel.json)), data generation scripts (`scripts/*.mjs`), and integrations with external services including Supabase, Stripe, Alipay, Google Analytics 4, and Vercel.

## Frontend Presentation Layer

The frontend is a React 18 application bootstrapped with Vite, emphasizing component modularity and internationalization.

### Entry Point and Component Architecture

The application initializes in [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx), which creates the root using `createRoot` and imports the **Lucide-React** icon set for consistent UI elements. The component hierarchy includes reusable elements such as `Hero`, `FilterPill`, `LanguageSwitch`, `AuthModal`, and `UserMenu`, all co-located in the main entry file.

Global styling resides in [`src/styles.css`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/styles.css), while component-scoped styles (such as [`src/community.css`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/community.css)) are imported directly where needed to optimize bundle size.

### State Management and Internationalization

Rather than using a global state library, the application relies on **custom React hooks** for side-effect management:

- `useGaPageViews` – Lazy-loads GA4 and emits `page_view` events via `window.gtag`
- `useBodyScrollLock` – Prevents background scrolling when modals are active
- `useCopy` – Handles clipboard interactions for sharing prompts

Text internationalization is implemented through a large `copy` object containing English and Chinese strings, accessed via helper functions `textFor` and `listFor` rather than a dedicated i18n library.

## Backend API Layer

All server-side logic follows the Vercel Serverless Functions pattern, with each endpoint exporting an async `handler(req, res)` function that the frontend consumes via standard `fetch` requests.

### Core API Endpoints

The backend exposes specific routes for distinct business functions:

- **`/api/generate-image`** – Orchestrates the image generation pipeline by first reserving credits through Supabase stored procedure `reserve_generation_usage`, then posting to `CIYUAN_BASE_URL/v1/images/generations`, and returning base64-encoded images.

- **`/api/me`** – Returns the authenticated user's profile including `credit_balance` and free-generation eligibility status.

- **`/api/favorites`** – Manages user-specific case favorites through add/remove operations backed by Supabase tables.

- **`/api/billing/*`** – Handles Stripe checkout sessions, Alipay integration, plan lookups, and credit pack purchases through endpoints like [`api/billing/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/billing/checkout.js).

- **`/api/admin/*`** – Provides administrative dashboards in [`api/admin/users.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/admin/users.js) for user management, metrics viewing, and manual credit adjustments.

- **`/api/community/*`** – Supports community features including QR code generation and status endpoints.

### Shared Utilities Library

The `api/_lib/` directory contains shared infrastructure code:

- **[`supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/supabase.js)** – Creates an admin client, parses bearer tokens via `getBearerToken`, and exposes `ensureProfileForUser` for profile upserts.
- **[`ga4.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/ga4.js)** – Wraps Google Analytics 4 server-side tracking.
- **[`billing.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/billing.js)** – Centralizes Stripe and Alipay operation logic.
- **[`community.test.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/community.test.js)** – Contains unit tests for community helper functions.

## Data and Authentication Flow

User identity and persistent data rely entirely on **Supabase**, configured in [`src/supabaseClient.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/supabaseClient.js) for client-side operations and [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js) for server-side admin tasks.

The authentication flow presents an `AuthModal` offering Google OAuth (via `supabase.auth.signInWithOAuth`) and Watcha OAuth (redirecting to `/api/auth/watcha/start`). All protected API routes validate sessions by extracting the bearer token from headers, verifying it through `client.auth.getUser`, and ensuring a profile record exists via `ensureProfileForUser`.

Database tables track profiles, membership tiers, credit balances, generation history, and user favorites, with row-level security policies enforced at the Supabase layer.

## Image Generation Pipeline

Image creation follows a credit-reservation pattern to prevent abuse and ensure payment integrity. When a user submits a prompt, the [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) handler executes:

1. Validates the user session and reserves a credit (or free generation slot) via the `reserve_generation_usage` stored procedure.
2. Posts the prompt to the **CIYUAN** service at `https://ciyuan.today/v1/images/generations`.
3. Returns the resulting image as a data URL (`data:image/jpeg;base64,...`) for immediate rendering in the UI.

This approach decouples the frontend from direct API key exposure while maintaining synchronous response times for the user.

## Payments and Billing

The architecture supports dual payment providers through abstraction in [`api/billing/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/billing/checkout.js). **Stripe** handles international credit pack purchases, while **Alipay** caters to Chinese users via custom checkout flows built with dynamically generated [`checkout.html`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/checkout.html) pages and hidden form submissions (`submitAlipayPaymentForm`). Both systems update the user's `credit_balance` in Supabase upon successful transaction verification.

## Build System and Deployment

**Vite** serves as the build tool, configured in [`vite.config.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/vite.config.js) with a custom plugin at `scripts/vite-local-api.mjs` that proxies API requests during local development to simulate the Vercel production environment.

The `scripts/` directory contains essential build utilities:

- `generate-site-data.mjs` – Generates static JSON files for prompt cases, templates, and style libraries.
- `generate-style-skill.mjs` – Packages the style library as a Vercel-compatible agent skill.
- `install-style-skill.mjs` – Facilitates local installation of the agent skill.

Deployment is configured through [`vercel.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/vercel.json), which defines serverless function boundaries and URL rewrites, enabling seamless edge deployment with automatic scaling.

## Agent Skill Integration

Beyond the web application, the repository includes a reusable **Style Library Skill** located at `agents/skills/gpt-image-2-style-library/`. This module allows Claude Code and Codex agents to access the prompt library programmatically, installable via the command displayed in the UI's `skillCopyCommand` component. The skill packaging logic resides in `scripts/generate-style-skill.mjs`, creating a bridge between the visual gallery and AI coding assistants.

## Implementation Examples

### Calling the Image Generation API

```javascript
async function generateTest(caseId, prompt) {
  const resp = await fetch('/api/generate-image', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json', 
      Authorization: `Bearer ${myToken}` 
    },
    body: JSON.stringify({ caseId, prompt })
  });
  const data = await resp.json();
  if (!data.ok) throw new Error(data.error);
  return data.image; // data URL ready for <img src={...} />
}

```

### Using the Supabase Client

```javascript
import { supabase, isSupabaseConfigured } from './supabaseClient';

if (isSupabaseConfigured) {
  const { data, error } = await supabase
    .from('profiles')
    .select('credit_balance')
    .eq('id', userId);
  // handle data / error
}

```

### Rendering a Hero Card Component

```jsx
function HeroCard({ caseItem, language, onOpen }) {
  return (
    <button
      className="heroCard"
      onClick={() => onOpen(caseItem)}
    >
      <img src={caseItem.image} alt={caseItem.imageAlt} />
      <span>{language === 'zh' ? '案例' : 'Case'} {caseItem.id}</span>
    </button>
  );
}

```

## Summary

- The awesome-gpt-image-2 repository uses a **three-layer architecture** separating Presentation (React), Backend Services (Vercel Functions), and Infrastructure (Supabase/CIYUAN).
- **Serverless functions** in `api/` handle authentication, billing, and image generation, with shared utilities centralized in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js).
- **Credit management** is enforced through Supabase stored procedures before calling the external CIYUAN GPT-Image-2 API.
- **Dual payment support** for Stripe and Alipay is abstracted through the billing layer while maintaining a unified credit balance system.
- The build pipeline uses **Vite with custom plugins**, and the deployment target is **Vercel** configured via [`vercel.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/vercel.json).
- An **agent skill** at `agents/skills/gpt-image-2-style-library/` extends utility to AI coding assistants beyond the web interface.

## Frequently Asked Questions

### What frontend framework powers the awesome-gpt-image-2 interface?

The application is built with **React 18** using Vite as the build tool. The entry point is [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx), which utilizes `createRoot` for concurrent React features and imports components like `Hero`, `AuthModal`, and `LanguageSwitch` to compose the UI.

### How does the repository handle user authentication?

Authentication is implemented through **Supabase Auth** with support for Google and Watcha OAuth providers. The `AuthModal` component triggers `supabase.auth.signInWithOAuth` for Google or redirects to `/api/auth/watcha/start` for Watcha. Server-side routes validate sessions using `getBearerToken` and `ensureProfileForUser` from [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js).

### What is the CIYUAN API's role in the architecture?

The **CIYUAN API** provides the actual GPT-Image-2 model inference. The [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) endpoint acts as a proxy, first reserving user credits via Supabase, then POSTing to `CIYUAN_BASE_URL/v1/images/generations`, and returning the generated image as a base64 data URL to the frontend.

### How are payments processed within the billing system?

The system supports **Stripe** for international payments and **Alipay** for Chinese users through endpoints in [`api/billing/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/billing/checkout.js). Both flows generate dynamic checkout pages, verify payment status with their respective APIs, and update the user's credit balance in Supabase upon confirmation.