How the Live Web Application for GPT-Image2 Works: Architecture and Data Flow

The GPT-Image2 live web application is a single-page React application built with Vite that leverages Supabase for authentication and credit management, while delegating image generation to the CIYUAN API through a transactional reservation system that prevents billing errors.

This article examines the freestylefly/awesome-gpt-image-2 repository to explain how the live web application for GPT-Image2 orchestrates front-end interactions, serverless API routes, and external services. The architecture follows a "static front-end plus serverless API" pattern where Vite bundles the React UI, Supabase handles SQL-level business logic, and CIYUAN provides the heavy-weight generative model.

Front-End Architecture: React, Vite, and Supabase Client

The user interface is a React application bootstrapped with Vite, with src/main.jsx serving as the entry point that renders the gallery, filter controls, language switcher, and authentication modal. All UI text is localized through a copy object supporting English and Chinese, while authentication state is managed via the Supabase client initialized in src/supabaseClient.js.

The Supabase client configuration includes automatic token refresh and session persistence:

// src/supabaseClient.js
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
export const isSupabaseConfigured = Boolean(supabaseUrl && supabaseAnonKey);
export const supabase = isSupabaseConfigured
  ? createClient(supabaseUrl, supabaseAnonKey, {
      auth: { autoRefreshToken:true, detectSessionInUrl:true, persistSession:true }
    })
  : null;

When users click "Generate Test", the React component initiates a POST request to /api/generate-image with the prompt and case ID. The application supports signing in with Google or Watcha, enabling the system to resolve user identities for credit tracking.

Backend API Routes and Image Generation

The back-end consists of serverless API routes that handle three primary concerns: image generation, user profile management, and payment processing. The core logic resides in api/generate-image.js, which implements a credit reservation pattern to ensure users are only charged for successful generations.

The Reservation Workflow

The API route api/generate-image.js executes the following steps:

  1. Authentication: Resolves the user via getAuthContext from api/_lib/supabase.js.
  2. Reservation: Calls the Supabase stored procedure reserve_generation_usage to atomically reserve a credit slot.
  3. Generation: Posts the prompt to https://ciyuan.today/v1/images/generations with the gpt-image-2 model.
  4. Completion: On success, calls complete_generation_reservation to deduct credits; on failure, calls release_generation_reservation to refund the reserved slot.

The reservation logic prevents race conditions and ensures that users are never charged for failed or interrupted requests:

// api/generate-image.js – reserveGeneration()
async function reserveGeneration(client, userId, caseId, prompt) {
  const { data, error } = await client.rpc('reserve_generation_usage', {
    p_user_id: userId,
    p_case_id: caseId,
    p_prompt: prompt,
    p_force_credit: false
  });
  if (error) {
    const msg = String(error.message || error.details || '').toUpperCase();
    if (msg.includes('CREDITS_REQUIRED')) {
      const err = new Error('CREDITS_REQUIRED');
      err.code = 'CREDITS_REQUIRED';
      throw err;
    }
    throw error;
  }
  const reservation = normalizeReservation(data);
  if (!reservation) throw new Error('RESERVATION_FAILED');
  return reservation;
}

After reserving the credit, the handler invokes the CIYUAN image model with specific parameters for quality and format:

async function generateImage(prompt) {
  const baseUrl = (process.env.CIYUAN_BASE_URL || 'https://ciyuan.today').replace(/\/$/, '');
  const res = await fetch(`${baseUrl}/v1/images/generations`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.CIYUAN_API_KEY}`,
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-image-2',
      prompt,
      n: 1,
      size: '1024x1024',
      quality: 'low',
      format: 'jpeg'
    })
  });
  const payload = await res.json().catch(() => ({}));
  if (!res.ok || !payload?.data?.[0]?.b64_json) throw new Error('Image generation failed');
  return `data:image/jpeg;base64,${payload.data[0].b64_json}`;
}

User Profiles and Billing Integration

The api/me.js route handles profile retrieval and updates, using getProfileById alongside the Supabase RPC get_user_account_usage to attach credit balances and recent transaction history. For monetization, the application integrates Alipay and Stripe through routes like api/community/alipay/checkout.js, which generate checkout sessions and validate orders before invoking Supabase RPCs to credit user balances.

End-to-End Data Flow

The complete interaction flow from page load to image display follows these steps:

  1. Initialization: React loads the UI and immediately calls GET /api/me to fetch the authenticated user's profile or establish an anonymous session.
  2. Gallery Population: Cases are fetched from Supabase tables (via internal endpoints) and rendered with filtering capabilities.
  3. Generation Request: Clicking Generate Test triggers POST /api/generate-image, which authenticates the user, reserves a credit via Supabase RPC, and forwards the request to CIYUAN.
  4. Response Handling: On success, the API returns a base64 JPEG (data:image/jpeg;base64,…) to the client, which displays the image and caches it in localStorage under the key gpt-image-2-generated-tests:v1 (storing the latest 12 images).
  5. Billing: The UI reflects the updated profile.creditBalance (fetched via /api/me); when credits deplete, users trigger checkout flows that update their balance through Supabase stored procedures.

Key Files in the Repository

Summary

  • The GPT-Image2 web application combines a React front-end with serverless API routes, using Supabase as the authoritative source for auth and credit state.
  • A reservation-based credit system in api/generate-image.js ensures users are only charged when the CIYUAN API successfully returns an image.
  • The CIYUAN API is called with the gpt-image-2 model, returning base64 JPEGs that are cached locally to improve perceived performance.
  • Supabase stored procedures (reserve_generation_usage, complete_generation_reservation, release_generation_reservation) handle atomic credit operations to prevent billing errors.
  • The architecture supports Google and Watcha authentication, with credit persistence across sessions via autoRefreshToken and persistSession configurations.

Frequently Asked Questions

How does the application prevent users from being charged for failed image generations?

The system implements a transactional reservation pattern. When a user initiates generation, api/generate-image.js calls the reserve_generation_usage RPC to temporarily hold a credit. Only upon successful completion of the CIYUAN API call does it invoke complete_generation_usage to finalize the deduction. If the external service returns an error or the request fails, release_generation_reservation is called immediately to refund the held credit, ensuring users are never charged for unsuccessful attempts.

What authentication methods does the GPT-Image2 web application support?

According to the source code in src/supabaseClient.js and api/_lib/supabase.js, the application supports authentication through Google and Watcha providers. The Supabase client is configured with detectSessionInUrl: true and persistSession: true to maintain login state across page refreshes, while autoRefreshToken: true handles token expiry automatically.

How does the application handle offline access or page refreshes?

The front-end caches generated images in the browser's localStorage using the key gpt-image-2-generated-tests:v1, preserving the latest 12 generations. Additionally, Supabase manages session persistence and credit bookkeeping server-side, so users retain their credit balances and authentication status even after closing and reopening the browser, provided they haven't cleared site data.

Where is the image generation actually performed?

While the React front-end handles the UI and credit display, the actual computational work occurs at CIYUAN's hosted API (https://ciyuan.today/v1/images/generations). The application's backend acts as a secure proxy, forwarding prompts with the gpt-image-2 model parameter and returning the resulting base64-encoded JPEG to the client without exposing the CIYUAN API key to the browser.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →