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

BE
3h ago
+258-10

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