Optimization

HTML Minification

Chování HTML response minification middleware, safety guards a integrační body.

Component purpose

HTML minification reduces output size by removing unnecessary whitespace and some optional closing tags. Minification is applied only to responses whose Content-Type contains text/html.

Pipeline position

In the current Framework::run(), HtmlMinifyMiddleware is registered as the last global middleware before the dispatch fallback, so it processes an already completed response after the previous middleware steps.

$pipeline = MiddlewarePipeline::create(
    [
        $this->container->get(RequestLoggingMiddleware::class),
        $this->container->get(BenchmarkMiddleware::class),
        $this->container->get(ErrorHandlingMiddleware::class),
        $this->container->get(PoweredByMiddleware::class),
        $this->container->get(HtmlMinifyMiddleware::class),
    ],
    $this->container->get(DispatchRequestHandler::class)
);

Activation strategy

Enable minification mainly for production responses where bandwidth matters. Keep it disabled in local development when HTML readability during debugging is more important than payload size.

Enabling and configuration

The middleware reads the feature flag from html_minify.enabled. The default value is false, so minification is disabled by default until the application explicitly enables it.

return [
    'html_minify' => [
        'enabled' => Env::bool('HTML_MINIFY_ENABLED', false),
    ],
];

Conditions that skip minification

The middleware returns the original response unchanged when minification is disabled, the response is not HTML, the body is empty, or the minifier returns the same text as the input. This minimizes unnecessary work and reduces the risk of side effects.

if (! $this->enabled()) {
    return $response;
}

if (! $this->isHtmlResponse($response)) {
    return $response;
}

$html = (string) $response->getBody();
if (trim($html) === '') {
    return $response;
}

HtmlMinifier algorithm

HtmlMinifier first temporarily preserves sensitive blocks (pre, textarea, script, style), then normalizes whitespace inside tags, compresses spaces and newlines through regex rules, removes selected optional closing tags, and finally restores the original content of the preserved blocks.

private const PRESERVED_TAGS = [
    'pre',
    'textarea',
    'script',
    'style',
];

Safe processing scope

The minifier operates only on response body text and does not parse DOM structure. Keep generated HTML valid and deterministic; avoid relying on fragile whitespace semantics outside preserved blocks.

Body and header changes

When the content changes, the middleware creates a new response body stream, removes the original Content-Length header and writes the new length. If the content does not change, the response remains unchanged.

return $response
    ->withBody(Stream::create($minified))
    ->withoutHeader('Content-Length')
    ->withHeader('Content-Length', (string) strlen($minified));

Caching and proxies

Because content bytes can change, keep minification order stable before downstream cache layers (reverse proxy/CDN). Recomputed Content-Length ensures HTTP framing stays correct after body rewrite.

Testing recommendations

Validate with representative templates: long forms, inline scripts, style blocks and CMS-driven markup. Assert response status, headers and semantic HTML output, not exact whitespace equality.

Dependencies

HtmlMinifyMiddleware uses only HtmlMinifier and Config. The minifier itself is a pure text transformation without a direct dependency on the request or the container.