gohugoio/hugo · error

invalid color code

Error message

invalid color code: %q

What it means

Returned by hexStringToColorGo when the input string (after stripping '#') has a length other than 3, 4, 6, or 8 characters. Valid hex colors are RGB (3), RGBA (4), RRGGBB (6), or RRGGBBAA (8); any other length is rejected before attempting hex.DecodeString.

Solutions

  1. Use a 3-, 6-, or 8-digit hex code (with optional leading #): #fff, #ffffff, #ffffffaa.
  2. Do not pass CSS named colors (red, blue) -- only hex is accepted.
  3. Count the hex digits after the #: must be 3, 4, 6, or 8.

Example fix

// before
[imaging]
bgColor = "#fffff"

// after
[imaging]
bgColor = "#ffffff"
Defensive patterns

Strategy: validation

Validate before calling

var validHexLen = map[int]bool{3: true, 4: true, 6: true, 8: true}
func isValidHexColor(s string) bool {
    s = strings.TrimPrefix(s, "#")
    if !validHexLen[len(s)] { return false }
    _, err := hex.DecodeString(padShortHex(s))
    return err == nil
}

Type guard

func isValidHexColorCode(s string) bool {
    s = strings.TrimPrefix(s, "#")
    if len(s) != 3 && len(s) != 4 && len(s) != 6 && len(s) != 8 { return false }
    for _, r := range s {
        if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) { return false }
    }
    return true
}

Prevention

When it happens

Trigger: Passing a malformed color string to any color config (imaging.bgColor, a #bg option in an image spec, or a color Param). E.g. "#ff" (2 chars), "#fffff" (5), "#12345" (5), or a non-hex length like "white".

Common situations: A typo in imaging.bgColor in hugo.toml (e.g. "#fffff" intended as ffffff), a template passing a named color instead of hex, a stray character dropping the length.

Related errors


AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09). Data as JSON: /api/errors/232a2dd3f45f04bc. Report an issue: GitHub.

Appendix: source

Thrown at resources/images/color.go:166

		return vv.ColorGo(), true, nil
	default:
		s, ok := hstrings.ToString(v)
		if !ok {
			return nil, false, nil
		}
		c, err := hexStringToColorGo(s)
		if err != nil {
			return nil, false, err
		}
		return c, true, nil
	}
}

func hexStringToColorGo(s string) (color.Color, error) {
	s = strings.TrimPrefix(s, "#")

	if len(s) != 3 && len(s) != 4 && len(s) != 6 && len(s) != 8 {
		return nil, fmt.Errorf("invalid color code: %q", s)
	}

	s = strings.ToLower(s)

	if len(s) == 3 || len(s) == 4 {
		var v strings.Builder
		for _, r := range s {
			v.WriteString(string(r) + string(r))
		}
		s = v.String()
	}

	// Standard colors.
	if s == "ffffff" {
		return color.White, nil
	}

	if s == "000000" {

View on GitHub (pinned to 52c9bd7908)