leptos-rs/leptos · error

use_matched called outside a matched Route

Error message

use_matched called outside a matched Route

What it means

use_matched returns the params of the currently matched Route and only works inside a component rendered within a matched route's Outlet context. Calling it where no route has matched (above the Routes tree, outside Router, or during 404 handling) panics.

Source

Thrown at router/src/hooks.rs:286

/// ```rust
/// # if false { // can't actually navigate, no <Router/>
/// let navigate = leptos_router::hooks::use_navigate();
/// navigate("/", Default::default());
/// # }
/// ```
#[track_caller]
pub fn use_navigate() -> impl Fn(&str, NavigateOptions) + Clone {
    let cx = use_context::<RouterContext>()
        .expect("You cannot call `use_navigate` outside a <Router>.");
    move |path: &str, options: NavigateOptions| cx.navigate(path, options)
}

/// Returns a reactive string that contains the route that was matched for
/// this [`Route`](crate::components::Route).
#[track_caller]
pub fn use_matched() -> Memo<String> {
    use_context::<Matched>()
        .expect("use_matched called outside a matched Route")
        .0
        .into()
}

View on GitHub (pinned to 32d20f6c9d)

Solutions

  1. Call `use_matched()` only from components rendered inside a matched route's view/outlet.
  2. If you need the current path outside a route, use `use_location()` inside a `<Router>` instead.
  3. For fallback/404 views, provide them as a route definition so they still have Matched context.

Example fix

// before
view! {
  <Router>
    <Breadcrumbs/> // uses use_matched() -> panics (no route context)
    <Routes/>
  </Router>
}

// after
view! {
  <Router>
    <Routes>
      <Route path=path!("/:id") view=move || view! { <Breadcrumbs/><Profile/> }/>
    </Routes>
  </Router>
}
Defensive patterns

Strategy: fallback

Validate before calling

let matched = use_context::<Matched>();
let path = matched.map(|m| m.0.get()).unwrap_or_default();

Type guard

fn matched_available() -> bool { use_context::<Matched>().is_some() }

Prevention

When it happens

Trigger: Calling `use_matched()` in a component rendered outside any route's render tree (e.g. a component above `<Routes>`, or a route that did not match). Also hit by components like `Redirect` used outside route context.

Common situations: Using `use_matched` in a global layout that isn't itself inside a `<Route>`/parent route view; using it in 404/fallback components that render without a matched route; tests without routing setup.

Related errors


AI-assisted analysis of leptos-rs/leptos@32d20f6c9d (2026-09-01). Data as JSON: /api/errors/54d899599aec00dd. Report an issue: GitHub.