Route to private services from Workers
This example shows how to use Workers VPC to create a centralized gateway that routes requests based on URL paths, provides authentication and rate limiting, and load balances across internal services.
- Multiple private APIs or services running in your VPC/virtual network (we'll use a user service and orders service)
- Cloudflare Tunnel configured and running (follow the Get Started guide to set up or create a tunnel from the dashboard ↗)
- Workers account with Workers VPC access
First, create services for your internal APIs using hostnames:
# Create user servicenpx wrangler vpc service create user-service \ --type http \ --tunnel-id <YOUR_TUNNEL_ID> \ --hostname user-api.internal.example.com
# Create orders servicenpx wrangler vpc service create order-service \ --type http \ --tunnel-id <YOUR_TUNNEL_ID> \ --hostname orders-api.internal.example.comNote the service IDs returned for the next step.
Update your wrangler.toml:
{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "api-gateway", "main": "src/index.js", "compatibility_date": "2024-01-01", "vpc_services": [ { "binding": "USER_SERVICE", "service_id": "<YOUR_USER_SERVICE_ID>" }, { "binding": "ORDER_SERVICE", "service_id": "<YOUR_ORDER_SERVICE_ID>" } ]}name = "api-gateway"main = "src/index.js"compatibility_date = "2024-01-01"
[[vpc_services]]binding = "USER_SERVICE"service_id = "<YOUR_USER_SERVICE_ID>"
[[vpc_services]]binding = "ORDER_SERVICE"service_id = "<YOUR_ORDER_SERVICE_ID>"In your Workers code, use the VPC Service bindings to route requests to the appropriate services:
export default { async fetch(request, env, ctx) { const url = new URL(request.url);
// Route to internal services if (url.pathname.startsWith('/api/users')) { const response = await env.USER_SERVICE.fetch("https://user-api.internal.example.com" + url.pathname); return response; } else if (url.pathname.startsWith('/api/orders')) { const response = await env.ORDER_SERVICE.fetch("https://orders-api.internal.example.com" + url.pathname); return response; }
return new Response('Not Found', { status: 404 }); },};Now, you can deploy and test your Worker:
npx wrangler deploy# Test user service requestscurl https://api-gateway.workers.dev/api/users
# Test orders service requestscurl https://api-gateway.workers.dev/api/orders- Add authentication and authorization
- Implement rate limiting
- Set up monitoring and alerting
- Explore other examples
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark