Skip to content

fix: raise BackendVarFormatError when a backend var is used in the UI - #7651

Merged
FarhanAliRaza merged 9 commits into
reflex-dev:mainfrom
darshjoshi:fix/7459-backend-field-literal-var
Nov 4, 2026
Merged

FarhanAliRaza merged 9 commits into
reflex-dev:mainfrom
darshjoshi:fix/7459-backend-field-literal-var

Conversation

@darshjoshi

@darshjoshi darshjoshi commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Description

Class access to a field with no frontend Var (a backend var such as State._secret, an is_var=False field, or any field of a mixin state) returns the raw Field. When that Field is passed where a Var gets built from a Python value, it reaches the end of LiteralVar.create (_create_literal_var), or of its var-data twin _get_all_var_data_without_creating_var_dispatch. Neither recognises a Field, so both fall through to the generic TypeError: Unsupported type ... for LiteralVar. That covers rx.Var.create([F]), rx.Var.create({"a": F}), rx.toast(F), rx.console_log(F), rx.image(src=F) and rx.data_table(data=F) from the issue. Formatting the same field with f"{F}" already raises a clear BackendVarFormatError from Field.__format__.

This PR follows the proposal in the issue and gives the LiteralVar path the same wording:

  • Field.__format__ now builds its message in a small helper, Field._no_frontend_var_error(). The text is unchanged.
  • Both LiteralVar fallthroughs check isinstance(value, Field) right before the generic TypeError and raise that error. The check runs only on the path that was about to fail, so supported values pay nothing. BackendVarFormatError is a VarTypeError, which is a TypeError, so except TypeError code still catches it.

test_backend_field_literal_var_reports_repr asserted the old generic message, so it is replaced by tests that expect BackendVarFormatError.

Before / After (F = S._secret, S a state with _secret: str = "x"):

# before (upstream/main d28eb2e0)
rx.Var.create([F]) -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. Tried to create a LiteralVar from Field(default='x', is_var=True, annotated_type=<class 'str'>).
rx.Var.create({"a": F}) -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. ...
rx.toast(F) rendered -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. ...
rx.console_log(F) rendered -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. ...
rx.image(src=F) rendered -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. ...
rx.data_table(data=F) rendered -> builtins.TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar. ...
f"{F}" (control) -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...

# after
rx.Var.create([F]) -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server and has no frontend value, so it cannot be used in the UI. Use S._secret.default_value() for its default value, declare it as ClassVar[...] for a constant shared by all sessions, or use a regular state var for a value the UI should show and update.
rx.Var.create({"a": F}) -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...
rx.toast(F) rendered -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...
rx.console_log(F) rendered -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...
rx.image(src=F) rendered -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...
rx.data_table(data=F) rendered -> reflex_base.utils.exceptions.BackendVarFormatError: Backend var 'S._secret' exists only on the server ...

The error still comes up where the Var is built (stringified or rendered), not at the rx.toast(...) / rx.image(...) call. That is the same place as before, but now with the explanation.

Other paths (#7732)

Later commits give the same error to the paths that do not go through LiteralVar:

Code Before After
rx.box(id=F) rendered TypeError: expected string or bytes-like object, got 'Field' BackendVarFormatError from Component.get_ref
app.add_page(index, title=F) (also description, image) ChildrenTypeError at compile time, with no frame from the app file BackendVarFormatError from add_page, at the user's line
rx.upload_files(upload_id="u", on_upload_progress=F) bound to a handler ValueError: Field(...) is not a valid event handler. BackendVarFormatError
str(F) + "px", "%s" % F, f"{F!s}" No error. The page gets the text Field(default=...)px. BackendVarFormatError from the new Field.__str__
f"{S.get_fields()['shown']}" (the field of a regular var) 'S.shown' has no frontend var (false) 'S.shown' is the field of a state var, not the var. Use S.shown to use it in the UI.

Field.__str__ also changes the error at the sites that used !s to show the field's repr: a class_name list, untyped Var item access, the internal Button variant and size checks, and event triggers (Invalid event chain / Invalid event). These sites now raise BackendVarFormatError, which names the var and the fix. print(State._x) now raises, and logging with %s prints a logging error. repr() and !r still give the Field text. The 0.10 upgrade guide is updated to match.

Not covered: a typed prop such as rx.heading(size=F). Component._post_init catches the TypeError and raises Invalid var passed for prop ... got value Field(...).

Tests:

  • tests/units/reflex_base/vars/test_base.py: LiteralVar.create(F), str(Var.create([F])), str(Var.create({"a": F})), and _get_all_var_data() on the list and dict literals (this reaches the var-data twin). Plus a mixin field case for the mixin wording.
  • tests/units/test_event.py: rx.toast(F) and rx.console_log(F).
  • tests/units/components/test_component.py: rx.image(src=F) and rx.data_table(data=F) rendered.

With vars/base.py reverted to main, all 10 new cases fail with the generic TypeError: Unsupported type <class 'reflex_base.vars.base.Field'> for LiteralVar (8 raised at base.py:1932, 2 at :2011). With the fix they pass.

Tests for the other paths:

  • tests/units/reflex_base/vars/test_base.py: f"{F}", f"{F!s}", str(F) and "%s" % F; the field of a regular var from get_fields(); untyped Var item access.
  • tests/units/test_event.py: on_upload_progress=F, and F as an event trigger.
  • tests/units/components/test_component.py: rx.box(id=F) rendered, and F in a class_name list.
  • tests/units/test_app.py: add_page with title, description or image set to F.
  • tests/units/components/core/test_upload.py: rx.get_upload_url(F).
  • tests/units/experimental/test_hooks.py: F passed to const, useCallback, useContext, useRef and useState.
  • tests/units/reflex_components_internal/components/base/test_button.py: F as a Button variant or size.

At 224db98cc:

$ uv run pytest tests/units/reflex_base/vars/test_base.py tests/units/test_event.py tests/units/components/test_component.py tests/units/test_app.py tests/units/components/core/test_upload.py tests/units/experimental/test_hooks.py tests/units/reflex_components_internal/components/base/test_button.py -k 'format_error or format_raises'
42 passed, 771 deselected, 1 warning in 0.32s

$ uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
Required test coverage of 72.0% reached. Total coverage: 80.86%
15504 passed, 64 skipped, 22 warnings in 263.63s (0:04:23)

The pre-commit hooks (ruff format, ruff check, codespell, update-pyi-files, pyright, ty) pass. reflex-release changelog-check and check-headings pass with the news fragments packages/reflex-base/news/+backend-var-literal-var.bugfix.md and news/+backend-var-page-meta.bugfix.md.

Closes #7459
Closes #7732

View guided diff

Field.__format__ now raises an error built by Field._no_frontend_var_error, so other code paths that reject a Field can reuse the same message.
A backend var (or a mixin field) passed where a Var is built from a Python value, such as rx.Var.create([State._secret]), rx.toast(State._secret) or rx.image(src=State._secret), reached the generic fallthrough of LiteralVar.create and _get_all_var_data_without_creating_var_dispatch and failed with TypeError: Unsupported type ... for LiteralVar. Both now raise the same BackendVarFormatError that formatting the field raises.
@darshjoshi
darshjoshi requested a review from a team as a code owner October 23, 2026 18:31
@greptile-apps

greptile-apps Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issue was found.

Summary

The PR gives clearer errors when a backend field is used where a frontend value is needed.

  • Backend-only fields get a clear error when Reflex needs a frontend value.
  • Page metadata rejects fields that have no frontend value.

No actionable new issues were found. No previous review threads were supplied.

Reviews (6) · Last reviewed commit: "test: cover backend vars passed to the e..." · Reviewed by Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 5 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

@codspeed

codspeed Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 14 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 148 untouched benchmarks


Comparing darshjoshi:fix/7459-backend-field-literal-var (224db98) with main (8fef24d)

Open in CodSpeed

@masenf masenf added the bug Something isn't working label Oct 27, 2026
@FarhanAliRaza FarhanAliRaza added the on deck PRs lined up to review / merge next label Nov 4, 2026
Build the LiteralVar fallthrough error in one helper, so both dispatchers
keep their previous complexity. Update the BackendVarFormatError docstring,
which is now raised outside string formatting, and the 0.10 upgrade guide,
which still quoted the old TypeError for a backend var used as a prop.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 3 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

FarhanAliRaza and others added 5 commits November 4, 2026 22:43
A backend var given as a component id, as on_upload_progress, or as page
title, description or image failed with an unrelated TypeError, ValueError
or ChildrenTypeError that did not name the var. These now raise
BackendVarFormatError. Page metadata is checked in add_page, so the error
points at the user's call.

A state var's field read from get_fields() no longer claims to have no
frontend var; the message says to use the var instead.

Add a test for get_upload_url with a backend var.
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
# Conflicts:
#	packages/reflex-base/src/reflex_base/event/__init__.py
… str()

Field.__str__ now raises the same error as Field.__format__, so str(F),
"%s" % F and f"{F!s}" no longer put the Field repr in the page. The
error sites that used !s to keep their own error (class_name lists,
untyped Var item access, Button variant/size, event triggers) now raise
BackendVarFormatError, which names the var and the fix. repr() and !r
still give the Field text.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 8 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Re-trigger cubic

@FarhanAliRaza FarhanAliRaza changed the title fix: raise BackendVarFormatError for a backend var in a LiteralVar fix: raise BackendVarFormatError when a backend var is used in the UI Nov 4, 2026
@FarhanAliRaza
FarhanAliRaza merged commit 1a7dda9 into reflex-dev:main Nov 4, 2026
170 checks passed
FarhanAliRaza pushed a commit that referenced this pull request Nov 11, 2026
…eck at runtime (#7818)

* Point to repr() when a backend var field is printed in server code

Since #7651, `str()` of a class-level backend var such as `State._secret`
raises `BackendVarFormatError`, so `print()`, `%` formatting and logging of
it in server code raise too, with a message that only talks about the UI.
The error now ends with how to inspect the field there, and the unreleased
#7651 changelog entry says that print and logging are affected.

Found in the reflex 0.11.0a1 pre-release testing (FINDING-037).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Skip the storage default_factory check on the runtime path

The compile calls a str-compatible `default_factory` to reject one that
produces browser storage. `_shared_storage_groups` reran the same compile
step in every backend worker's first event, calling each such factory once
more per worker. The runtime path now skips the factory call; the compile
still checks.

Found in the reflex 0.11.0a1 pre-release testing (FINDING-038).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

---------

Co-authored-by: Claude <[email protected]>
masenf added a commit that referenced this pull request Nov 11, 2026
…eck at runtime (#7818)

* Point to repr() when a backend var field is printed in server code

Since #7651, `str()` of a class-level backend var such as `State._secret`
raises `BackendVarFormatError`, so `print()`, `%` formatting and logging of
it in server code raise too, with a message that only talks about the UI.
The error now ends with how to inspect the field there, and the unreleased

Found in the reflex 0.11.0a1 pre-release testing (FINDING-037).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Skip the storage default_factory check on the runtime path

The compile calls a str-compatible `default_factory` to reject one that
produces browser storage. `_shared_storage_groups` reran the same compile
step in every backend worker's first event, calling each such factory once
more per worker. The runtime path now skips the factory call; the compile
still checks.

Found in the reflex 0.11.0a1 pre-release testing (FINDING-038).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

---------

Co-authored-by: Claude <[email protected]>
(cherry picked from commit 10dd495)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working on deck PRs lined up to review / merge next

Projects

None yet

3 participants