getRequestProtocol function

String? getRequestProtocol(
  1. H4Event event
)

Get the request protocol

Determines whether the request was made over HTTP or HTTPS. First checks the 'x-forwarded-proto' header (commonly set by proxies), then falls back to checking if the connection itself is secure.

router.get("/home", (event) {
  String protocol = getRequestProtocol(event); // "http" or "https"
  // Use protocol in constructing URLs or making security decisions
});

Returns "https" for secure connections, "http" otherwise.

Implementation

String? getRequestProtocol(H4Event event) {
  // Check forwarded protocol header first (set by proxies/load balancers)
  final forwardedProto =
      event.node["value"]?.headers.value("x-forwarded-proto");
  if (forwardedProto != null) {
    return forwardedProto.toLowerCase();
  }

  // Fall back to checking if the connection itself is secure
  final isSecure = event.node["value"]?.connectionInfo?.localPort == 443 ||
      (event.node["value"]?.headers.value('x-forwarded-ssl') == 'on') ||
      (event.node["value"]?.headers.value('x-forwarded-scheme') == 'https');
  return isSecure ? "https" : "http";
}