serve method

Future<HttpServer> serve({
  1. InternetAddress? address,
  2. int port = 8080,
  3. SecurityContext? securityContext,
  4. int? maxRequestBodyBytes,
})

Binds to a native dart:io HttpServer and begins serving API and SSR requests.

Listens on address (defaults to InternetAddress.anyIPv4) and port (default 8080). If securityContext is provided, uses HttpServer.bindSecure for TLS/HTTPS termination.

maxRequestBodyBytes optionally enforces a strict size limit on incoming request bodies, short-circuiting oversized payloads with an HTTP 413 response before full buffering.

Tracks active in-flight requests to support graceful zero-downtime shutdown via close.

Example

final server = await router.serve(
  address: InternetAddress.loopbackIPv4,
  port: 3000,
  maxRequestBodyBytes: 10 * 1024 * 1024, // 10MB limit
);
print('Server running on port ${server.port}');

Implementation

Future<HttpServer> serve({
  InternetAddress? address,
  int port = 8080,
  SecurityContext? securityContext,
  int? maxRequestBodyBytes,
}) async {
  final bindAddress = address ?? InternetAddress.anyIPv4;
  final server = securityContext != null
      ? await HttpServer.bindSecure(bindAddress, port, securityContext)
      : await HttpServer.bind(bindAddress, port);

  _servers.add(server);

  server.listen((ioReq) async {
    if (_isClosing) {
      try {
        ioReq.response.statusCode = HttpStatus.serviceUnavailable;
        ioReq.response.headers.contentType = ContentType.json;
        ioReq.response.add(utf8.encode(jsonEncode({
          'error': 'Server is shutting down',
          'statusCode': HttpStatus.serviceUnavailable,
        })));
        await ioReq.response.close();
      } catch (_) {}
      return;
    }

    final completer = Completer<void>();
    _inFlightRequests.add(completer);
    try {
      await handleIoRequest(ioReq, maxRequestBodyBytes: maxRequestBodyBytes);
    } finally {
      if (!completer.isCompleted) {
        completer.complete();
      }
      _inFlightRequests.remove(completer);
    }
  });

  return server;
}