IP Worker is a lightweight Cloudflare Worker that provides the client's IP address and country information. It eliminates the need for expensive services by leveraging Cloudflare's infrastructure to handle these requests efficiently.
- IP Address Fetching: Get the client's IP address directly.
- Country Detection: Detect the client's country based on IP.
- CORS Support: Fully CORS-compliant for cross-origin requests.
- Lightweight: No heavy dependencies, just simple and effective code.
- Cloudflare Account: Create an account at Cloudflare.
git clone <repository-url>
cd ip-workerInstall the required dependencies using npm:
npm installAuthenticate with your Cloudflare account:
npm run loginDeploy your worker to Cloudflare:
npm run deployAfter deployment, Cloudflare will provide a URL for your worker. Use this URL to fetch IP and country data.
The worker responds to HTTP requests with JSON data containing the client's IP address and country.
Make a GET request to the deployed worker's URL.
{
"country": "US",
"ip": "203.0.113.195"
}The worker includes CORS headers to support cross-origin requests. Example headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-TypeUse Wrangler to run the worker locally:
npm run devRun tests with Vitest:
npm testThe main worker code is located in src/index.ts:
export default {
async fetch(request, env, ctx): Promise<Response> {
const ip = request.headers.get('CF-Connecting-IP');
const country = request.headers.get('CF-IPCountry');
const response = Response.json({ country, ip });
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
return response;
},
} satisfies ExportedHandler<Env>;- Wrangler: Cloudflare Worker CLI.
- TypeScript: Typed JavaScript.
- Vitest: Test framework for Cloudflare Workers.
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Feel free to open an issue or submit a pull request.