Skip to main content

Gemini Web2API - Cloudflare Workers Deployment Documentation

中文文档 | Quick Setup Guide (~5 min, zero to deployed)
New here? Follow the Quick Setup Guide: cookie, KV, secrets, deploy, verify, first request.

Project Introduction

Gemini Web2API runs on Cloudflare Workers and converts the Gemini web interface to an OpenAI-compatible API. No server or API key is required.

Core Features

  • Zero-cost deployment is based on Cloudflare Workers free plan (100,000 requests per day)
  • Global acceleration is achieved through deployment to Cloudflare’s 300+ global edge nodes
  • OpenAI compatible: Compatible with /v1/chat/completions and /v1/models endpoints
  • Streaming output: SSE (Server-Sent Events) streaming response
  • Multi-fingerprint rotation uses 8 browser fingerprints + 6 language preferences randomly rotated to reduce detection probability
  • Multi-Cookie rotation supports configuring multiple Google account cookies, randomly selected for use
  • Concurrent safety provides request-level configuration isolation, eliminating configuration crosstalk in high-concurrency scenarios
  • Tool call support is compatible with OpenAI Function Calling format
  • ProxyScrape Auto Proxy Rotation automatically fetches free proxies from ProxyScrape (timeout ≤ 200ms API or GitHub raw), auto-tests connectivity against gemini.google.com:443, and supports HTTP/SOCKS4/SOCKS5 via cloudflare:sockets. It uses best-of-2 scoring so the fastest verified proxy wins most requests while slower ones still get periodic health checks. The pool updates every 24 hours (Cron Trigger + background refresh), candidate lists are cached in memory to avoid redundant upstream fetches, and everything falls back to a direct connection on failure.

Applicable Scenarios

  • Provide free Gemini API for NextChat, Cherry Studio, ChatBox and other clients
  • Used as Gemini model backend in tools like WorkBuddy
  • Personal learning, research and small project AI capability access

Quick Deployment

Step 1: Log in to Cloudflare

  1. Open Cloudflare Dashboard
  2. Log in to your Cloudflare account (free registration available if you don’t have one)
  3. Go to the left menu Workers & Pages

Step 2: Create Worker

  1. Click Create ApplicationCreate Worker
  2. Give your Worker a name (e.g., api)
  3. Click the Deploy button
  4. Click the Edit Code button
  5. Clear the default code in the editor
  6. Paste the complete project code into the editor
  7. Click Save and Deploy in the top right corner

Step 3: Get Test Address

After successful deployment, your API address is:
For example: https://api.geminai.workers.dev

Step 4: Verify Deployment

Visit the following address in your browser:
If you see a JSON response similar to the following, deployment is successful:

Client Configuration

NextChat (ChatGPT-Next-Web)

Cherry Studio

ChatBox

Using curl for Testing


Environment Variable Configuration (Optional)

Configure in Cloudflare Dashboard → Workers → Your Worker → Settings → Variables → Environment Variables:

Gemini Configuration

Performance Optimization

Auto Proxy Pool & 24h Update Configuration

Proxy Rotation Modes

Set PROXY_ROTATION_MODE to one of four values to control how the next proxy is chosen for each request. All modes share the same adaptive scoring layer: every successful request updates the proxy’s latency with an EWMA (α = 0.3) and resets its fail counter, so a proxy that just slowed down drops in rank within ~3 requests, and a recovered one climbs back. Every failed request increments fails, which halves that proxy’s score (exponential cooldown), and any proxy that hits 2 cumulative fails is evicted from the pool. Score formula (used by best-of-2 and weighted):
  • Latency defaults to 1000 ms if missing or non-positive, so the latency=0 path (pretest disabled) no longer collapses to 1/0 = Infinity.
  • fails resets to 0 on the first successful request, so a proxy recovers fully after one good call.
Examples:
Invalid values are ignored and logged as a WARN; the worker keeps the default (best-of-2).

How the 24-Hour Update Works:

  1. Cloudflare Cron Trigger (Recommended):
    • When deploying via Wrangler, wrangler.jsonc already configures "triggers": { "crons": ["0 0 * * *"] }.
    • In Cloudflare Dashboard: Go to Workers & Pages → Your Worker → TriggersCron TriggersAdd Cron Trigger → enter 0 0 * * * (every 24 hours at 00:00 UTC).
  2. On-Demand Auto-Update:
    • Even if you don’t configure a Cron Trigger, the Worker automatically checks the timestamp on incoming requests. If 24 hours have passed since the last update, it refreshes the proxy pool in the background using ctx.waitUntil() without slowing down user requests!
  3. Cloudflare KV Persistence (Recommended with Cron):
    • Bind a KV namespace named PROXY_KV to your Worker. Verified proxies will be cached in KV across all edge data center instances!
    • The daily cron refresh runs in its own invocation with its own subrequest budget, tests the pool, and writes the verified result to KV — so user requests on any isolate load the warm pool from KV instead of paying the cold-start test cost.
    • Setup: npx wrangler kv namespace create PROXY_KV, then paste the returned namespace id into the kv_namespaces block of wrangler.jsonc (a placeholder is already there).
    • Without KV, the cron refresh only warms the cron’s own throwaway isolate; each user-facing isolate still does its own cold-start refresh.
  4. Proxy Endpoints (all require a valid API key, same auth as /v1 endpoints):
    • GET /proxies: View proxy pool status, active proxy count, latencies, and last/next update times.
    • POST /proxies/refresh or GET /proxies/refresh: Force an immediate re-fetch and test of the proxy pool.
    • GET /debug/proxies: Detailed pool diagnostics — per-proxy health (healthy/flaky), latency, fail counts, rotation scores (highest first), and internal state (candidate cache, refresh due, rotation mode).
    • GET /health: Includes live proxy status in the health check JSON.
  5. In-Memory Candidate Caching (Free):
    • After fetching from the primary/fallback source, the parsed candidate list is cached per Worker Isolate (free, no KV cost).
    • TTL equals PROXY_UPDATE_INTERVAL_HOURS (24h default). Within one cycle, refresh attempts reuse the cache and skip both the ProxyScrape and GitHub raw fetches.
    • Manual /proxies/refresh calls bypass the cache (force=true) and always re-fetch.
    • Empty results never poison the cache, so a transient primary failure won’t lock the pool.

Anonymous requests hit Gemini’s rate limits quickly (HTTP 429). A valid cookie lowers that risk and improves Pro model routing.

Obtaining Steps

  1. Open Chrome/Edge browser
  2. Visit https://gemini.google.com/app and log in to your Google account
  3. Press F12 to open developer tools
  4. Go to the Application tab
  5. On the left, select Cookieshttps://gemini.google.com
  6. Find the following Cookies and copy their values:
    • __Secure-1PSID
    • __Secure-3PSID
    • SAPISID
  7. Combine into a complete Cookie string:

Multi-account Configuration

If you have multiple Google accounts, you can separate multiple Cookies with |:
Each request will randomly select a Cookie to use, greatly reducing the probability of a single account being rate-limited.

Updating BL Version

If you encounter HTTP 405: Method Not Allowed error, it means the Gemini frontend has been updated, and you need to synchronize the build tag update:
  1. Open https://gemini.google.com/app in browser
  2. Press F12Network tab
  3. Search for boq_assistant in any request’s URL
  4. Copy the latest version number, for example:
  5. Update the environment variable GEMINI_BL or the geminiBl configuration item in the code

Multi-fingerprint Rotation Mechanism

This program has a built-in browser fingerprint rotation system, where each request randomly selects different browser identifiers:

Security Recommendations

  1. Modify default API Key: Change now-and-then in apiKeys to your own key
  2. Set rate limiting: Adjust RATE_LIMIT_MAX based on actual usage
  3. Regularly update Cookie: Google Cookies expire and need regular replacement
  4. Do not share Cookie: Cookie is equivalent to your Google account credentials

Frequently Asked Questions

Q: Returns empty response from server

Cause: NextChat streaming parsing issue.
Solution: Make sure you’re using the latest version of the code (SSE format has been fixed).

Q: Returns HTTP 429: Too Many Requests

Cause: Gemini rate limiting, anonymous request frequency limits are stricter.
Solution: Configure valid COOKIE_STRING and SAPISID.

Q: Returns HTTP 405: Method Not Allowed

Cause: BL version expired.
Solution: Update geminiBl configuration (see the “Updating BL Version” section above).

Q: Returns invalid api key

Cause: Client API Key configuration error.
Solution: Check if the client is configured with the correct API Key (default now-and-then).

Q: WorkBuddy usage shows crosstalk

Cause: Multi-model concurrent requests share global configuration.
Solution: Current version has resolved this issue through request-level configuration isolation.

Supported Model List

Supports overriding thinking mode via @think= parameter:
  • gemini-3.6-flash@think=0: Flash model + deep thinking
  • gemini-3.1-pro@think=4: Pro model + automatic thinking

Changelog


License

This project is based on the original project gemini-web2api ported, following the original project’s open source license.