You can control and intercept outbound network requests from a container by configuring properties on your Container subclass.
Core Configuration Properties
enableInternet: Set to true to allow outbound internet access. If false, all outbound requests are blocked unless explicitly handled.interceptHttps: When true, HTTPS requests are intercepted to allow inspection or modification.allowedHosts: An array of hostnames (e.g., ['google.com']) that are permitted to make outbound requests.deniedHosts: An array of hostnames that are explicitly blocked. If a host is in both allowedHosts and deniedHosts, it is blocked.
Outbound Handlers
You can define how specific outbound requests are handled using three levels of priority:
outboundByHost: A mapping of hostnames to handler functions. This is the highest priority.outboundHandlers: A mapping of named handlers. You can trigger these from your application code using container.setOutboundByHost(host, handlerName, params).outbound: A catch-all function that handles any outbound request not matched by the previous two methods.
import { Container, getContainer } from '@cloudflare/containers';
export class MyContainer extends Container {
defaultPort = 8080;
enableInternet = false;
interceptHttps = true;
allowedHosts = ['api.stripe.com', 'google.com', 'github.com'];
deniedHosts = ['evil.com'];
}
// 1. Highest priority: Specific host mapping
MyContainer.outboundByHost = {
'google.com': (req, env, ctx) => {
return new Response('intercepted google for ' + ctx.containerId);
},
};
// 2. Named handlers (invoked via setOutboundByHost)
MyContainer.outboundHandlers = {
async github(req, env, ctx) {
return new Response('github handler, ' + ctx.params?.hello);
},
};
// 3. Lowest priority: Catch-all
MyContainer.outbound = req => {
return new Response(`catch-all for ${new URL(req.url).hostname}`);
};
export default {
async fetch(request, env) {
const container = getContainer(env.MY_CONTAINER);
// Trigger a named handler for a specific host with custom parameters
await container.setOutboundByHost('github.com', 'github', { hello: 'world' });
return await container.fetch(request);
},
};