Skip to content

feat: typed access to dynamic route args with rx.route_arg - #7943

Open
benedikt-bartscher wants to merge 6 commits into
reflex-dev:mainfrom
benedikt-bartscher:feat/typed-route-arg
Open

benedikt-bartscher wants to merge 6 commits into
reflex-dev:mainfrom
benedikt-bartscher:feat/typed-route-arg

Conversation

@benedikt-bartscher

@benedikt-bartscher benedikt-bartscher commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Adding a page at /post/[pid] installs rx.State.pid at runtime (State.setup_dynamic_args). Type checkers can't see that attribute, so code that reads a dynamic route arg the documented way needs an ignore:

rx.heading(rx.State.pid)  # ty: ignore[missing-attribute] / pyright: ignore[reportAttributeAccessIssue]

There is currently no typed alternative. router.page.params is deprecated and only typed as Any past .params, and router.url has no path params.

This PR adds two functions that return the same vars, typed:

rx.heading(rx.route_arg("pid"))  # StringVar, for [pid] or the optional [[pid]]
rx.foreach(rx.route_catch_all(), rx.text)  # ArrayVar[list[str]], for [[...splat]]

A regular arg and the catch-all get separate functions because the name alone doesn't decide the type: /post/[splat] is a regular arg named splat. Each function checks that the installed arg is of its kind.

  • An arg that no added page has, or has as the other kind, raises a new DynamicRouteArgNotFoundError. It is an AttributeError, like the attribute access it replaces, and its message says what is installed and points to the other function.
  • Like rx.State.pid, the arg has to be installed when it is accessed.
  • Both functions return a var for building components, not the value in an event handler or a computed var.

Why module-level functions. An earlier version of this PR added them as classmethods on BaseState. That made route_arg and route_catch_all framework members of every state. A state var or computed var named route_arg, an event handler named route_catch_all, or a page at /x/[route_arg] all work on main, and all would have raised. Module-level functions reserve no names. They resolve against rx.State, the only root state an app can have outside tests.

A _route_arg_type helper now classifies installed route vars for these functions and for _dynamic_route_arg_types. A new RouteRegex.SPLAT_ARG constant names the catch-all arg for them and for get_route_args. reflex-base gets the exception and the constant; reflex's existing floor reflex-base >= 0.11.1.dev0 covers both.

Tests

  • tests/units/test_state.py resolves the functions against a fresh root state, so no route args leak onto rx.State. It compares vars with equals and covers:
    • a substate and an optional [[lang]] arg;
    • the catch-all and a regular [splat];
    • the complete error messages;
    • a state that declares route_arg and route_catch_all, and a page at /x/[route_arg].
  • tests/type_checking/state.py asserts the types; it passes under the ty hook, ty 0.0.107, and pyright-type-checking-3.11/3.14.
  • The dynamic routing docs and the news fragments for reflex and reflex-base cover the new functions.

All pre-commit hooks, full-repo pyright, the docs app tests and reflex-release changelog-check pass.

🤖 Generated with Claude Code

Adding a page at `/post/[pid]` installs `rx.State.pid` at runtime, so type
checkers do not know the attribute and code using it needs an ignore.
`rx.State.route_arg("pid")` returns the same var as a `StringVar`, and
`rx.State.route_arg("splat")` the one of the `[[...splat]]` catch-all as
an `ArrayVar[list[str]]`. An arg no added page declares raises
DynamicRouteArgNotFoundError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable new issues were found.

Summary

Adds typed access to dynamic route arguments through rx.route_arg() and rx.route_catch_all().

  • Dynamic route arguments now have typed rx accessors.

Reviews (6) · Last reviewed commit: "Replace the route arg classmethods with ..." · Reviewed by Greptile

Comment thread reflex/state.py Resolved
Comment thread reflex/state.py Resolved
Comment thread tests/units/test_app.py Resolved
…full errors

The name alone does not decide a route arg's type: `/post/[splat]` is a
regular arg named `splat`, so `route_arg(Literal["splat"])` promised an
ArrayVar for a StringVar, and `route_arg(name: str)` a StringVar for the
catch-all when called with a `str` that is "splat". `route_arg(name)` is
now the regular arg as a StringVar and `route_catch_all()` the
`[[...splat]]` catch-all as an ArrayVar[list[str]]; each checks the
installed arg is of its kind.

reflex imports DynamicRouteArgNotFoundError from the unreleased
reflex-base, so its floor is reflex-base >= 0.11.1.dev0. The tests compare
the complete error messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codspeed

codspeed Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 6.43%

2 warnings

⚠️ 16 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

⚠️ 3 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

❌ 3 regressed benchmarks
✅ 143 untouched benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_route_matching[1000] 90 ms 96.8 ms -6.93%
❌ test_route_matching[100] 9.4 ms 10.1 ms -6.88%
❌ test_route_matching[10] 1.2 ms 1.3 ms -5.46%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing benedikt-bartscher:feat/typed-route-arg (51c5592) with main (df7f157)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@benedikt-bartscher
benedikt-bartscher marked this pull request as ready for review November 19, 2026 21:00
@benedikt-bartscher
benedikt-bartscher requested review from a team and Alek99 as code owners November 19, 2026 21:00

@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

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

View guided diff | Re-trigger cubic

Comment thread docs/pages/dynamic_routing.md Resolved
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benedikt-bartscher

Copy link
Copy Markdown
Contributor Author

About the CodSpeed failure: this looks like runner noise rather than this change. Details:

  • Each run flags a different benchmark. On 67b6c16 it was test_state_access[read_cached_computed] (−5.09%), which is untouched on 0edfed4. On 0edfed4 it is test_proxy_list_mutation (−4.52%).
  • Both times, CodSpeed warns that the significantly changed benchmark "ran on different hardware" than its baseline.
  • The PR only adds classmethods to BaseState. Neither benchmark calls them.
  • Locally (walltime, same main base with and without this PR), read_cached_computed is 1.3 ms on both. test_proxy_list_mutation is 419 µs on the base and 395 µs with the PR.

Could a maintainer acknowledge it on CodSpeed?

benedikt-bartscher and others added 3 commits November 20, 2026 09:48
…ch_all

`rx.State.route_arg` and `rx.State.route_catch_all` made both names
framework members of every state: a state var or computed var named
`route_arg`, an event handler named `route_catch_all`, or a page at
`/x/[route_arg]` worked before and raised once they existed. The
accessors are now the module-level functions `rx.route_arg(name)` and
`rx.route_catch_all()`, resolved against `rx.State`, the only root state
an app can have. They reserve no names.

Their docstrings and the docs say that they return a var for building
components, not the value in an event handler or a computed var. The
docs show `rx.route_arg("pid")` in the `/post/[pid]` example, and the
catch-all accessor moves to the Catch-All Routes section with an
`rx.foreach(rx.route_catch_all(), rx.text)` example.

The errors say what is installed and point to the other accessor.
`_route_arg_type` classifies an installed route var for these and for
`_dynamic_route_arg_types`, and `RouteRegex.SPLAT_ARG` names the
catch-all arg for them and for `get_route_args`.

The tests move to test_state.py, next to the code. They resolve the
accessors against a fresh root state rather than `rx.State` or the shared
`EmptyState`, compare the vars with `equals`, and cover a substate, an
optional `[[lang]]` arg, the errors, and a state that declares
`route_arg` and `route_catch_all`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benedikt-bartscher benedikt-bartscher changed the title feat: typed access to dynamic route args with rx.State.route_arg feat: typed access to dynamic route args with rx.route_arg Nov 21, 2026

@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.

1 issue found across 11 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/units/test_state.py">

<violation number="1" location="tests/units/test_state.py:4478">
P2: This fixture restores only `reflex.state.State`, but each test registers `RouteArgRoot` (and the first test registers `RouteArgSubState`) in shared state registries that survive fixture teardown. Later tests therefore see stale route-test classes, making the suite order-dependent; isolate these tests with a registration context and restore the shared state registries and related caches in teardown.

(Based on your team's feedback about restoring shared State registries.) .</violation>
</file>

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

View guided diff | Re-trigger cubic

Comment thread tests/units/test_state.py
class RouteArgRoot(BaseState):
"""Root state standing in for `rx.State`."""

monkeypatch.setattr("reflex.state.State", RouteArgRoot)

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.

P2: This fixture restores only reflex.state.State, but each test registers RouteArgRoot (and the first test registers RouteArgSubState) in shared state registries that survive fixture teardown. Later tests therefore see stale route-test classes, making the suite order-dependent; isolate these tests with a registration context and restore the shared state registries and related caches in teardown.

(Based on your team's feedback about restoring shared State registries.) .

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/units/test_state.py, line 4478:

<comment>This fixture restores only `reflex.state.State`, but each test registers `RouteArgRoot` (and the first test registers `RouteArgSubState`) in shared state registries that survive fixture teardown. Later tests therefore see stale route-test classes, making the suite order-dependent; isolate these tests with a registration context and restore the shared state registries and related caches in teardown.

(Based on your team's feedback about restoring shared State registries.) .</comment>

<file context>
@@ -4455,6 +4458,125 @@ def test_router_field_names_are_reserved(name):
+    class RouteArgRoot(BaseState):
+        """Root state standing in for `rx.State`."""
+
+    monkeypatch.setattr("reflex.state.State", RouteArgRoot)
+    return RouteArgRoot
+
</file context>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant