getzola/zola · error

Failed to convert bytes to string : {}

Error message

Failed to convert bytes to string : {}

What it means

The `html` minification helper in components/site/src/minify.rs minifies HTML via the `minify` crate and then converts the minified bytes back to a String with `std::str::from_utf8`. If the resulting bytes are not valid UTF-8, it bails with this message including the Utf8Error. This indicates the minifier produced output that is not valid UTF-8 for the given input.

Source

Thrown at components/site/src/minify.rs:13

use errors::{Result, bail};
use minify_html::{Cfg, minify};

pub fn html(html: String) -> Result<String> {
    let mut cfg = Cfg::new();
    cfg.keep_html_and_head_opening_tags = true;
    cfg.minify_css = true;
    cfg.minify_js = false;

    let minified = minify(html.as_bytes(), &cfg);
    match std::str::from_utf8(&minified) {
        Ok(result) => Ok(result.to_string()),
        Err(err) => bail!("Failed to convert bytes to string : {}", err),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // https://github.com/getzola/zola/issues/1292
    #[test]
    fn can_minify_html() {
        let input = r#"
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>

View on GitHub (pinned to 61d3082821)

Solutions

  1. Re-save the HTML input file as UTF-8 without BOM
  2. Find the offending byte sequence from the embedded Utf8Error (it includes the byte index) and fix that character in the source file
  3. Verify the file has no mixed encodings (e.g. `file` or `iconv` to detect)
  4. If caused by the minify crate, pin/upgrade the minify dependency

Example fix

// before
$ cat page.html | minify  # file saved as Windows-1252
// after
$ iconv -f WINDOWS-1252 -t UTF-8 page.html > page.html
Defensive patterns

Strategy: try-catch

Validate before calling

if let Err(e) = std::str::from_utf8(html.as_bytes()) {
    return Err(anyhow!("input is not UTF-8 at byte {}: {e}", e.valid_up_to()));
}

Type guard

fn is_valid_utf8(bytes: &[u8]) -> bool { std::str::from_utf8(bytes).is_ok() }

Try / catch

match minify_to_string(html) {
    Ok(out) => write(out),
    Err(e) if e.to_string().contains("Failed to convert bytes") => {
        // fall back to unminified input
        write(html.to_string());
    }
    Err(e) => return Err(e),
}

Prevention

When it happens

Trigger: Calling the `html` minify function with input whose minified output contains invalid UTF-8 byte sequences — typically caused by non-UTF-8 input encodings or a minifier bug on multibyte content.

Common situations: Sites with HTML files saved in Latin-1/Windows-1252 or containing malformed byte sequences; certain multibyte characters interacting with the minifier.

Related errors


AI-assisted analysis of getzola/zola@61d3082821 (2026-09-03). Data as JSON: /api/errors/8a134e9b5c240c38. Report an issue: GitHub.