reflex-dev/reflex · error · TypeError
Cannot serialize color that contains non-literal vars.
Error message
Cannot serialize color that contains non-literal vars.
What it means
Color.json() must emit a CSS custom property, which requires color/alpha/shade to be literal values. If any of them is a Var (non-literal), serialization is impossible and TypeError is raised.
Source
Thrown at packages/reflex-base/src/reflex_base/vars/color.py:158
self._var_data,
)
def json(self) -> str:
"""Get the JSON representation of the var.
Returns:
The JSON representation of the var.
Raises:
TypeError: If the color is not a valid color.
"""
color, alpha, shade = map(
get_python_literal,
(self._var_value.color, self._var_value.alpha, self._var_value.shade),
)
if color is None or alpha is None or shade is None:
msg = "Cannot serialize color that contains non-literal vars."
raise TypeError(msg)
if (
not isinstance(color, str)
or not isinstance(alpha, bool)
or not isinstance(shade, int)
):
msg = "Color is not a valid color."
raise TypeError(msg)
return f"var(--{color}-{'a' if alpha else ''}{shade})"
View on GitHub (pinned to 45b8ed5ab7)
Solutions
- Resolve the Var to a literal before constructing the color (compute the chosen color in state and use a static lookup)
- Use rx.color with literal strings/integers only
- If the value varies per render, keep it as a Var expression rather than calling .json()
Example fix
# before
color = rx.color(State.color_name, shade=5) # State.color_name is a Var
# after
color = rx.color("grass", shade=5) # literal; pick dynamically in state instead Defensive patterns
Strategy: type-guard
Validate before calling
from reflex.vars.base import get_python_literal parts = [get_python_literal(p) for p in (color._var_value.color, color._var_value.alpha, color._var_value.shade)] assert all(p is not None for p in parts), 'color contains non-literal vars'
Type guard
def is_literal_color(color) -> bool:
from reflex.vars.base import get_python_literal
v = color._var_value
return all(get_python_literal(p) is not None for p in (v.color, v.alpha, v.shade)) Prevention
- Only pass literal strings/ints to rx.color
- Resolve state-driven choices into literals inside state before building colors
When it happens
Trigger: Building a color from Var-driven components, e.g. rx.color(f"{my_var}", shade=n) where the color name or shade resolves to a Var, then rendering/serializing it.
Common situations: Dynamically picking a color from state and passing it where a serializable literal color is required (e.g. theme serialization).
Related errors
- Color is not a valid color.
- The component `{child_name}` can only be a child of the comp
- No valid JSON representation for {self}
- The keys and values of the object must be literal vars to ge
- Array elements must be of type LiteralVar, not {type(element
AI-assisted analysis of reflex-dev/reflex@45b8ed5ab7 (2026-08-28).
Data as JSON: /api/errors/6c320a6cb4ae534d.
Report an issue: GitHub.