Skip to main content

Deploy Gemini Web2API on Cloudflare Workers

New here? Follow the Quick Setup Guide: cookie, KV, secrets, deploy, verify, first request.

Overview

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

  • Runs on the Cloudflare Workers free plan (100,000 requests per day), so it costs nothing
  • Deploys to Cloudflare’s 300+ edge nodes worldwide
  • OpenAI-compatible: works with the /v1/chat/completions and /v1/models endpoints
  • Streams responses via SSE (Server-Sent Events)
  • Rotates 8 browser fingerprints and 6 language preferences per request to reduce detection
  • Rotates multiple Google account cookies, picking one at random per request
  • Isolates configuration per request, so concurrent requests don’t cross-talk
  • Supports tool calls in OpenAI Function Calling format
  • Fetches free proxies from ProxyScrape (via a ≤200ms API or GitHub raw), tests each against gemini.google.com:443, and supports HTTP/SOCKS4/SOCKS5 through cloudflare:sockets. Best-of-2 scoring sends most requests through the fastest verified proxy while slower ones still get periodic health checks. The pool refreshes every 24 hours (Cron Trigger + background refresh), candidate lists stay cached in memory to avoid refetching, and the worker falls back to a direct connection when everything fails.

Use cases

  • A free Gemini backend for NextChat, Cherry Studio, ChatBox, and similar clients
  • A Gemini backend for tools like WorkBuddy
  • Personal learning, research, and AI features in small projects

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 Application → Create 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

Test with curl


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 the Cloudflare Dashboard: Workers & Pages → Your Worker → Triggers → Cron Triggers → Add Cron Trigger → enter 0 0 * * * (every 24 hours at 00:00 UTC).
  2. On-demand auto-update
    • Even without a Cron Trigger, the worker 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 get 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 also includes live proxy status in the health check JSON.
  5. In-memory candidate caching (free, no KV cost)
    • After fetching from the primary or fallback source, the parsed candidate list is cached per Worker Isolate.
    • 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.
  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 Cookies → https://gemini.google.com
  6. Find the following Cookies and copy their values:
    • __Secure-1PSID
    • __Secure-3PSID
    • SAPISID
  7. Combine them into a complete Cookie string:

Multiple accounts

If you have multiple Google accounts, you can separate multiple Cookies with |:
Each request draws a cookie at random, so a single account is less likely to hit rate limits.

Update the BL version

If you get HTTP 405: Method Not Allowed, the Gemini frontend has been updated and you need to sync the build tag:
  1. Open https://gemini.google.com/app in browser
  2. Press F12 → Network 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

How fingerprint rotation works

Each request picks a fresh set of browser identifiers:

Security

  1. Change the default API key: replace now-and-then in apiKeys with your own key
  2. Set rate limiting: adjust RATE_LIMIT_MAX based on actual usage
  3. Update cookies regularly: Google cookies expire and need regular replacement
  4. Don’t share your cookie: it’s as sensitive as your Google account credentials

License

This is a port of gemini-web2api, distributed under the original project’s open-source license.