How the awesome-gpt-image-2 Backend API Works: A Complete Technical Guide

The awesome-gpt-image-2 backend API is a serverless Next.js application that orchestrates AI image generation, user authentication, and payment processing through RESTful endpoints in the api/ directory, leveraging Supabase for data persistence and Apimart for image generation.

This repository implements a production-ready backend architecture using Next.js API routes deployed as serverless functions. The system coordinates external services including Supabase for database operations, Apimart for AI image generation, and multiple payment providers to deliver a complete image generation platform.

Architecture Overview

The backend follows a serverless function architecture where each file in the api/ directory represents an independent HTTP endpoint. This design pattern separates concerns into distinct routes: authentication handlers, generation pipelines, billing webhooks, and administrative tools. All routes share common utilities centralized in api/_lib/ to ensure consistent database connections, error handling, and external service integrations.

Core API Routes and Functionality

User Authentication and Profile Management

The authentication layer handles OAuth flows and session management through three primary endpoints:

  • api/me.js – Retrieves the current authenticated user's profile using the Supabase session
  • api/auth/watcha/start.js – Initiates the Watcha OAuth flow by generating the authorization URL
  • api/auth/watcha/callback.js – Processes the OAuth callback from Watcha, exchanges the code for tokens, and establishes the user session

The authentication system relies on api/_lib/supabase.js to validate session cookies and retrieve the current user.id for permission enforcement across protected routes.

Image Generation Pipeline

The core functionality centers on asynchronous image generation through a three-endpoint workflow:

api/generate-image.js accepts POST requests containing prompts, image sizes, and model selections. This endpoint:

  1. Validates the user's authentication via api/_lib/supabase.js
  2. Forwards the generation request to api/_lib/apimart.js (the external AI service wrapper)
  3. Creates a job record in Supabase via api/_lib/generation.js
  4. Returns a job ID for client-side polling

api/generation/status.js handles GET requests to check the current state of a generation job by querying the Supabase database for the associated metadata and status.

api/generation/callback.js serves as a webhook receiver that accepts asynchronous updates from the Apimart service when image generation completes, updating the job record with the final image URL.

Favorites and Community Features

User content management operates through api/favorites.js, which provides CRUD operations for saved images. This endpoint validates the session cookie, then performs database operations to add or remove images from the user's favorites collection.

Community-related functionality resides in api/community/*, handling QR-code generation, status endpoints, and Alipay integration for community transactions.

Billing and Subscription Management

The payment infrastructure under api/billing/* supports dual payment processors:

  • Stripe integration – Handles subscription creation, customer portal management, and checkout sessions
  • Alipay integration – Processes Chinese payment flows through api/billing/alipay/notify.js, which validates signatures and updates user credit balances

The api/_lib/billing.js helper centralizes credit adjustment logic, while api/_lib/alipay.js manages SDK interactions and signature verification for webhook security.

Administrative Endpoints

Administrative oversight is provided by api/admin/* routes, including:

  • api/admin/users.js – Lists and manages user accounts
  • api/admin/metrics.js – Retrieves platform usage statistics
  • Credit adjustment endpoints for manual balance corrections
  • Community refund management tools

Shared Utility Libraries (api/_lib)

The api/_lib/ directory contains service wrappers that abstract external dependencies:

  • api/_lib/supabase.js – Creates authenticated Supabase clients using request cookies, enabling row-level security and user identification
  • api/_lib/apimart.js – Wraps the external image-generation API with retry logic and error normalization
  • api/_lib/generation.js – Manages job lifecycle states, metadata persistence, and polling coordination
  • api/_lib/watcha.js – Handles OAuth token exchange and user profile retrieval from the Watcha service
  • api/_lib/alipay.js – Builds payment requests and verifies webhook signatures using Alipay's SDK
  • api/_lib/ga4.js – Tracks events to Google Analytics for usage monitoring

Request Lifecycle and Data Flow

Every request traverses a standardized pipeline:

  1. Request Entry – Client sends HTTP request to /api/[route]
  2. Auth & Session – Route imports api/_lib/supabase.js to validate cookies and extract user.id
  3. Business Logic – Handler invokes specialized libraries (e.g., api/_lib/apimart.js for generation)
  4. External Services – Libraries communicate with Apimart, Supabase, or payment processors
  5. Response – Endpoint returns JSON payloads or HTTP redirects; long-running jobs utilize the status endpoint or webhook callbacks for async updates

Practical API Usage Examples

Generate a new image using the generation endpoint:

curl -X POST https://your-domain.com/api/generate-image \
  -H "Content-Type: application/json" \
  -d '{
        "prompt": "A futuristic cityscape at sunset",
        "size": "1024x1024",
        "model": "stable-diffusion-v2"
      }'

Check the status of an asynchronous generation job:

curl https://your-domain.com/api/generation/status?id=12345

Add an image to the authenticated user's favorites:

curl -X POST https://your-domain.com/api/favorites \
  -H "Content-Type: application/json" \
  -d '{"imageId":"12345"}' \
  -b "next-auth.session-token=YOUR_SESSION_COOKIE"

Initiate the Watcha OAuth authentication flow:

curl https://your-domain.com/api/auth/watcha/start

Process an Alipay payment webhook (payload structure):

{
  "out_trade_no": "order_9876",
  "trade_status": "TRADE_SUCCESS",
  "total_amount": "9.99"
}

The webhook endpoint api/billing/alipay/notify.js validates this payload, updates the user's credit balance via api/_lib/billing.js, and returns a 200 OK response.

Summary

  • Serverless Architecture – Each api/ file represents an independent Next.js API route handling specific functionality
  • External Integrations – Apimart powers AI generation, Supabase manages persistence, and Stripe/Alipay handle payments
  • Async Workflow – Image generation uses a polling/status endpoint pattern plus webhooks (api/generation/callback.js) for completion notifications
  • Modular Libraries – api/_lib/ utilities centralize database connections, payment processing, and OAuth flows
  • Security – Session validation via Supabase cookies enforces authentication across all protected endpoints

Frequently Asked Questions

What technology stack powers the awesome-gpt-image-2 backend API?

The backend is built on Next.js API routes running as serverless functions, with Supabase providing PostgreSQL database functionality and real-time subscriptions. External AI capabilities come from the Apimart image generation service, while payment processing supports both Stripe (international) and Alipay (Chinese markets). All authentication relies on Supabase Auth with cookie-based session management.

How does the image generation workflow handle asynchronous processing?

When a client posts to api/generate-image.js, the system immediately returns a job ID while delegating the actual generation to Apimart via api/_lib/apimart.js. Clients poll api/generation/status.js to check progress, or the system receives webhook notifications at api/generation/callback.js when Apimart completes the task. The api/_lib/generation.js utility tracks all job states in Supabase, bridging the gap between the synchronous API and the asynchronous AI service.

Which payment providers are supported by the billing system?

The billing module supports Stripe for credit card subscriptions and customer portal management, plus Alipay for Chinese payment processing. The api/billing/checkout.js route creates payment sessions for both providers, while api/billing/alipay/notify.js handles Alipay's asynchronous webhook notifications. Credit balances are managed atomically through api/_lib/billing.js to prevent race conditions during concurrent top-ups.

How is user authentication implemented across endpoints?

All protected routes import api/_lib/supabase.js to create an authenticated Supabase client using the request's session cookie. This client provides the current user.id and enforces row-level security policies defined in Supabase. For OAuth flows, api/_lib/watcha.js manages the token exchange, while the standard email/password or magic link flows use Supabase Auth's native methods.

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 →