A configurable CORS proxy Cloudflare Worker that can forward requests to any target endpoint while adding the necessary CORS headers. This worker solves CORS issues by acting as a proxy between your frontend application and backend APIs that don't support CORS.
- π§ Fully Configurable: All settings via environment variables/secrets
- π― Wildcard Path Matching: Support for patterns like
/api/*and/auth/*/callback - π Multiple Origin Support: Allow requests from multiple domains
- π Dynamic HTTP Methods: Automatically handles all HTTP methods based on request headers
- π¦ Payload Override: Optional feature to replace response body for non-CORS endpoints
- π Multi-Environment: Support for development, staging, and production deployments
- β‘ GitHub Actions Integration: Automated deployment with secret management
| Variable | Type | Description | Example |
|---|---|---|---|
TARGET_ENDPOINT |
Secret | The backend endpoint to proxy to | https://api.example.com |
ALLOWED_ORIGINS |
Secret | JSON array of allowed origins | ["https://myapp.com", "https://dev.myapp.com"] |
ALLOWED_PATHS |
Secret | JSON array of path patterns | ["/api/*", "/auth", "/webhook/*"] |
| Variable | Type | Default | Description |
|---|---|---|---|
PAYLOAD_OVERRIDE |
Secret | null |
Override response payload for endpoints without CORS |
CORS_MAX_AGE |
Variable | 86400 |
Cache duration for preflight requests (seconds) |
ADDITIONAL_HEADERS |
Secret | {} |
JSON object for extra CORS headers |
- Cloudflare Account: Sign up at cloudflare.com
- Cloudflare API Token: Create with "Edit Cloudflare Workers" permissions
- Node.js: Version 18 or higher
- Wrangler CLI: Install globally with
npm install -g wrangler
-
Clone the repository:
git clone <repository-url> cd cors-proxy-cloudflare-worker
-
Install dependencies:
npm install -g wrangler
-
Login to Cloudflare:
wrangler login
-
Set your secrets locally:
# Required secrets wrangler secret put TARGET_ENDPOINT wrangler secret put ALLOWED_ORIGINS wrangler secret put ALLOWED_PATHS # Optional secrets wrangler secret put PAYLOAD_OVERRIDE wrangler secret put ADDITIONAL_HEADERS
-
Test locally:
wrangler dev
-
Deploy manually:
# Deploy to development wrangler deploy --env development # Deploy to production wrangler deploy --env production
Add the following secrets to your GitHub repository (Settings β Secrets and variables β Actions):
CLOUDFLARE_API_TOKEN=your_cloudflare_api_token
CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id
TARGET_ENDPOINT=https://your-api.example.com
ALLOWED_ORIGINS=["https://yourapp.com", "https://dev.yourapp.com"]
ALLOWED_PATHS=["/api/*", "/auth", "/federation"]
CLOUDFLARE_WORKER_NAME=my-cors-proxy
PAYLOAD_OVERRIDE={"message": "CORS proxy active"}
CORS_MAX_AGE=3600
ADDITIONAL_HEADERS={"X-Custom-Header": "value"}
The workflow automatically deploys based on:
- Push to
mainβ Production environment - Push to
stagingβ Staging environment - Push to
developβ Development environment - Manual trigger β Choose environment
You can trigger manual deployments from the GitHub Actions tab:
- Go to your repository's
Actionstab - Select "Deploy CORS Proxy Worker"
- Click "Run workflow"
- Choose your target environment
- Click "Run workflow"
// Environment configuration
TARGET_ENDPOINT = "https://api.example.com"
ALLOWED_ORIGINS = ["https://myapp.com"]
ALLOWED_PATHS = ["/api/*"]TARGET_ENDPOINT = "https://signin.aws.amazon.com/federation"
ALLOWED_ORIGINS = ["https://myapp.github.io", "https://localhost:3000"]
ALLOWED_PATHS = ["/federation"]TARGET_ENDPOINT = "https://gateway.example.com"
ALLOWED_ORIGINS = [
"https://app.example.com",
"https://admin.example.com",
"https://staging.example.com"
]
ALLOWED_PATHS = [
"/api/v1/*",
"/api/v2/*",
"/auth/*",
"/webhooks/stripe",
"/health"
]TARGET_ENDPOINT = "https://legacy-api.example.com"
ALLOWED_ORIGINS = ["https://newapp.com"]
ALLOWED_PATHS = ["/legacy/*"]
PAYLOAD_OVERRIDE = '{"message": "Request processed via CORS proxy"}'TARGET_ENDPOINT = "https://api.example.com"
ALLOWED_ORIGINS = ["https://app.com"]
ALLOWED_PATHS = ["/api/*"]
ADDITIONAL_HEADERS = {
"X-Proxy-Version": "1.0",
"X-Custom-Header": "cors-proxy"
}
CORS_MAX_AGE = 7200The worker supports simple wildcard patterns:
| Pattern | Matches | Doesn't Match |
|---|---|---|
/api/* |
/api/users, /api/posts |
/api, /api/v1/users |
/auth/*/callback |
/auth/google/callback, /auth/github/callback |
/auth/callback, /auth/google/token |
/exact/path |
/exact/path only |
/exact/path/more |
/* |
Any single-level path | Multi-level paths |
// Before (CORS error)
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => console.error('CORS Error:', error));
// After (using CORS proxy)
fetch('https://your-worker.workers.dev/api/data')
.then(response => response.json())
.then(data => console.log('Success:', data));fetch('https://your-worker.workers.dev/api/secure', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify({ key: 'value' })
});-
404 Errors
- Check that your request path matches one of the
ALLOWED_PATHSpatterns - Verify wildcard patterns are correct (
/api/*not/api/**)
- Check that your request path matches one of the
-
CORS Still Blocked
- Ensure the request origin is listed in
ALLOWED_ORIGINS - Check that origins match exactly (including protocol and port)
- Ensure the request origin is listed in
-
Deployment Failures
- Verify all required GitHub secrets are set
- Check Cloudflare API token has correct permissions
- Ensure
CLOUDFLARE_ACCOUNT_IDis correct
-
Secret Setting Errors
- Make sure JSON arrays/objects are properly formatted
- Check for trailing commas in JSON configuration
Enable debug logging by adding console logs to your worker:
// Add to worker.js for debugging
console.log('Request path:', url.pathname);
console.log('Allowed paths:', config.allowedPaths);
console.log('Origin:', request.headers.get('Origin'));
console.log('Allowed origins:', config.allowedOrigins);cors-proxy-cloudflare-worker/
βββ worker.js # Main worker code
βββ wrangler.toml # Wrangler configuration
βββ .github/
β βββ workflows/
β βββ deploy.yml # GitHub Actions workflow
βββ README.md # This file
βββ package.json # Optional: if you have dependencies
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Cloudflare Workers Documentation
- Wrangler CLI Documentation
- GitHub Actions Documentation
- CORS Documentation
- Use the development environment for testing configuration changes
- Monitor worker logs in the Cloudflare dashboard for debugging
- Set up multiple workers for different services/environments
- Consider using custom domains for production deployments
- Regular backup of your configuration as JSON files
π Ready to deploy? Follow the setup instructions above and start proxying those CORS-blocked requests!