AIAI Club
← Back to articles
ENGLISH GUIDE

Using Cloudflare Worker to Build a Reverse Proxy for Direct Gemini API Access in Mainland China Without a VPN

How can servers in mainland China call Gemini directly without a proxy? The web’s most popular practical tutorial: a few dozen lines of open-source JavaScript code to deploy an edge reverse proxy for free on Cloudflare, enabling millisecond-level direct connections.

1. Why Is a Reverse Proxy Needed?

Production servers in mainland China encounter network blocking when accessing generativelanguage.googleapis.com.
Using Cloudflare’s global edge nodes, we can forward requests to Google with a few lines of simple middleware code. Servers in mainland China only need to request your own Cloudflare domain to connect smoothly.

2. Minimal Code Walkthrough

Create a Worker in Cloudflare, paste the following code, and bind a custom domain:
```javascript
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
url.hostname = 'generativelanguage.googleapis.com'
const newReq = new Request(url, request)
return fetch(newReq)
}
```
After deployment, replace the baseUrl in the code with the domain you bound, and calls from mainland China will be unobstructed from then on!

This English translation is based on a Chinese source article. Prices are approximate where stated and conditions should be confirmed with the official provider or seller.