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/completionsand/v1/modelsendpoints - 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 viacloudflare: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
- Open Cloudflare Dashboard
- Log in to your Cloudflare account (free registration available if you don’t have one)
- Go to the left menu Workers & Pages
Step 2: Create Worker
- Click Create Application → Create Worker
- Give your Worker a name (e.g.,
api) - Click the Deploy button
- Click the Edit Code button
- Clear the default code in the editor
- Paste the complete project code into the editor
- Click Save and Deploy in the top right corner
Step 3: Get Test Address
After successful deployment, your API address is:https://api.geminai.workers.dev
Step 4: Verify Deployment
Visit the following address in your browser: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:Authentication Related
Gemini Configuration
Performance Optimization
Auto Proxy Pool & 24h Update Configuration
Proxy Rotation Modes
SetPROXY_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=0path (pretest disabled) no longer collapses to1/0 = Infinity. failsresets to 0 on the first successful request, so a proxy recovers fully after one good call.
WARN; the worker keeps the default (best-of-2).
How the 24-Hour Update Works:
- Cloudflare Cron Trigger (Recommended):
- When deploying via Wrangler,
wrangler.jsoncalready configures"triggers": { "crons": ["0 0 * * *"] }. - In Cloudflare Dashboard: Go to Workers & Pages → Your Worker → Triggers → Cron Triggers → Add Cron Trigger → enter
0 0 * * *(every 24 hours at 00:00 UTC).
- When deploying via Wrangler,
- 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!
- 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
- Cloudflare KV Persistence (Recommended with Cron):
- Bind a KV namespace named
PROXY_KVto 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 namespaceidinto thekv_namespacesblock ofwrangler.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.
- Bind a KV namespace named
- Proxy Endpoints (all require a valid API key, same auth as
/v1endpoints):GET /proxies: View proxy pool status, active proxy count, latencies, and last/next update times.POST /proxies/refreshorGET /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.
- 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/refreshcalls 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.
How to Get Gemini Cookie
Why Do You Need Cookie?
Anonymous requests hit Gemini’s rate limits quickly (HTTP 429). A valid cookie lowers that risk and improves Pro model routing.Obtaining Steps
- Open Chrome/Edge browser
- Visit https://gemini.google.com/app and log in to your Google account
- Press F12 to open developer tools
- Go to the Application tab
- On the left, select Cookies →
https://gemini.google.com - Find the following Cookies and copy their values:
__Secure-1PSID__Secure-3PSIDSAPISID
- Combine into a complete Cookie string:
Multi-account Configuration
If you have multiple Google accounts, you can separate multiple Cookies with|:
Updating BL Version
If you encounterHTTP 405: Method Not Allowed error, it means the Gemini frontend has been updated, and you need to synchronize the build tag update:
- Open https://gemini.google.com/app in browser
- Press F12 → Network tab
- Search for
boq_assistantin any request’s URL - Copy the latest version number, for example:
- Update the environment variable
GEMINI_BLor thegeminiBlconfiguration 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
- Modify default API Key: Change
now-and-theninapiKeysto your own key - Set rate limiting: Adjust
RATE_LIMIT_MAXbased on actual usage - Regularly update Cookie: Google Cookies expire and need regular replacement
- 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 thinkinggemini-3.1-pro@think=4: Pro model + automatic thinking