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/completionsand/v1/modelsendpoints - 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 throughcloudflare: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
- 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
Test with curl
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 the Cloudflare Dashboard: 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 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.
- 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
- Cloudflare KV persistence (recommended with cron)
- Bind a KV namespace named
PROXY_KVto 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 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 /healthalso includes live proxy status in the health check JSON.
- 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/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 you need a cookie
Anonymous requests hit Gemini’s rate limits quickly (HTTP 429). A valid cookie lowers that risk and improves Pro model routing.Get the cookie
- 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 them into a complete Cookie string:
Multiple accounts
If you have multiple Google accounts, you can separate multiple Cookies with|:
Update the BL version
If you getHTTP 405: Method Not Allowed, the Gemini frontend has been updated and you need to sync the build tag:
- 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
How fingerprint rotation works
Each request picks a fresh set of browser identifiers:Security
- Change the default API key: replace
now-and-theninapiKeyswith your own key - Set rate limiting: adjust
RATE_LIMIT_MAXbased on actual usage - Update cookies regularly: Google cookies expire and need regular replacement
- Don’t share your cookie: it’s as sensitive as your Google account credentials