GPT-Image2 Web Application Backend Technologies: Complete Serverless Stack Analysis
The GPT-Image2 backend is a Node.js serverless API built on Vercel that orchestrates Supabase for data persistence, Apimart for AI image generation, Stripe and Alipay for payment processing, and Google Analytics for telemetry.
The freestylefly/awesome-gpt-image-2 repository implements a production-ready micro-service architecture for handling AI image generation workflows. Understanding the specific GPT-Image2 web application backend technologies reveals how the system manages authentication, credit reservations, third-party API orchestration, and multi-currency payment processing within a serverless environment.
Core Runtime and Serverless Framework
Node.js with ES Modules
The backend executes exclusively on Node.js using ES module syntax (import/export). Every API route handler resides in the api/ directory and runs as an isolated serverless function. The runtime configuration in package.json specifies "type": "module", ensuring consistent module resolution across the entire codebase.
Vercel Serverless Functions
Vercel Serverless Functions provide the HTTP entry point for each backend operation. The platform automatically maps files like api/generate-image.js and api/billing/checkout.js to distinct HTTPS endpoints. This architecture eliminates server management while scaling individual routes independently based on demand.
Database and Authentication with Supabase
The backend relies on Supabase (@supabase/supabase-js) for PostgreSQL database operations, user authentication via JWT bearer tokens, and row-level security policies. The system maintains a singleton admin client pattern to optimize connection reuse across concurrent requests.
In api/_lib/supabase.js, the getSupabaseAdminClient() function initializes a service-role client with session persistence disabled for serverless environments:
// api/_lib/supabase.js
import { createClient } from '@supabase/supabase-js';
export function getSupabaseAdminClient() {
const { url, serviceRoleKey, configured } = getSupabaseConfig();
if (!configured) return null;
if (!adminClient) {
adminClient = createClient(url, serviceRoleKey, {
auth: { autoRefreshToken: false, persistSession: false }
});
}
return adminClient;
}
The singleton pattern prevents connection pool exhaustion during high-traffic periods by reusing the admin client across all API routes.
AI Image Generation via Apimart
Credit Reservation System
Before invoking external AI services, the backend verifies user credits through Supabase RPC calls. The reserveGeneration function in api/generate-image.js executes the reserve_generation_usage stored procedure to atomically check balances and lock credits:
// api/generate-image.js
export async function reserveGeneration(client, profile, 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: Boolean(profile?.isSuperAdmin)
});
if (error) { /* …handle credit errors… */ }
const reservation = normalizeReservation(data);
if (!reservation) throw new Error('RESERVATION_FAILED');
return reservation;
}
This database-level transaction guarantees that users cannot exceed their allocated generation quotas during race conditions.
Apimart Service Integration
The actual image generation delegates to Apimart through a custom wrapper in api/_lib/apimart.js. The submitApimartGeneration function submits prompts to the external service and normalizes response payloads:
// api/_lib/apimart.js
export async function submitApimartGeneration({ apiKey, prompt, language = 'en', webhook = '' }) {
const { baseUrl } = getApimartConfig();
const response = await fetch(`${baseUrl}/v1/images/generations`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify(buildApimartGenerationPayload(prompt, { language, webhook }))
});
const payload = await response.json();
if (!response.ok) throw upstreamError(response, payload);
return { taskId: extractApimartTaskId(payload), status: 'submitted' };
}
The wrapper abstracts Apimart-specific error formats and extracts task IDs for asynchronous polling.
Payment Processing Architecture
Stripe for Global Subscriptions
Stripe handles recurring billing and checkout sessions for international users. The api/billing/checkout.js route creates subscription-mode sessions that store stripe_customer_id references in the Supabase profiles table:
// api/billing/checkout.js (excerpt)
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${appUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${appUrl}/cancel`
});
Alipay SDK for Chinese Markets
For Chinese customers, the backend integrates the Alipay SDK (alipay-sdk) through api/billing/alipay/checkout.js. This implementation handles payment creation, refund operations, and asynchronous notification verification via Alipay's public key cryptography.
Analytics and Observability
The system tracks usage metrics through the Google Analytics Data API (@google-analytics/data). Located in api/_lib/ga4.js, the analytics module sends conversion events and generation metrics to GA4 properties. The Google Auth Library (google-auth-library) facilitates OAuth token exchanges for service account authentication, as implemented in scripts/google-analytics-oauth.mjs.
Development and Testing Infrastructure
Vite manages environment variable loading via vite.config.js, exposing configuration to both the frontend SPA and backend API routes. The project employs the Node.js native test runner (invoked via node --test) to execute unit tests for API helpers, eliminating external testing framework dependencies.
Summary
- Node.js with ES modules powers the runtime execution on Vercel's serverless platform.
- Supabase provides PostgreSQL storage, JWT authentication, and credit reservation stored procedures.
- Apimart serves as the external AI image generation provider, wrapped by custom utility functions.
- Stripe and Alipay SDK handle global and Chinese payment flows respectively.
- Google Analytics Data API records telemetry through authenticated service accounts.
- Vite and the Node.js test runner support development workflows and environment management.
Frequently Asked Questions
What database does GPT-Image2 use for user data and credits?
The backend uses Supabase (PostgreSQL) to store user profiles, membership tiers, and generation credits. The reserve_generation_usage RPC function in Supabase enforces atomic credit deductions before any Apimart API calls occur.
How does the GPT-Image2 backend handle payments for different regions?
International users process payments through Stripe checkout sessions configured for subscription billing, while Chinese users utilize the Alipay SDK with distinct endpoints in api/billing/alipay/checkout.js to handle localized currency and refund workflows.
Is the GPT-Image2 backend built on serverless architecture?
Yes. The entire backend runs as Vercel Serverless Functions using Node.js, where each file in the api/ directory automatically becomes an isolated HTTPS endpoint. This design requires stateless client initialization for services like Supabase to prevent connection leaks.
What service actually generates the AI images?
The backend delegates image creation to Apimart, an external AI generation platform. The api/_lib/apimart.js wrapper manages authentication, payload construction, and task ID extraction for asynchronous generation status polling.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →