API Reference

The routing library provides the following functions, classes, and attributes. Import functions and classes from routing.router, or use from routing import router. Component classes have their own modules, as shown below.

Router Configuration

When adding the routing library as a dependency, in the Anvil IDE, click the "edit" icon next to the routing library in the dependencies list. This will allow you to change the configuration options.

Config Options:

sitemap
If False, disables the automatic /sitemap.txt route. Defaults to False.
robots
If False, disables the automatic /robots.txt route. Defaults to False.
debug_logging
If True, enables verbose routing logs in both client and server app logs. Defaults to False.
raise_on_data_error
Controls whether the data loader reports failures through Anvil's exception handler. Failures also set routing_context.error and emit data_error. Setting this to False does not suppress navigation error handling: a failed initial load still opens the route's error_form or raises if none is defined. Defaults to True.
routes_module
The module where your routes are defined (e.g. utils.routes). Defaults to routes.

routes_module

The router automatically imports your routes module. By default, it looks for a module named routes. You do not need to explicitly import your routes module in client or server code.

If your routes are defined in a different module (e.g. utils.routes), set this option to the correct module name.

Setting routes_module is the simplest way to support discovery on both the client and server. Keep that module safe to import in both environments.

Functions

navigate(*, path=None, params=None, query=None, hash=None, replace=False, nav_context=None, form_properties=None)
navigate(path, **kws)
navigate(url, **kws)
navigate(routing_context, **kws)
Navigates to a new page using the destination route's scroll settings.
launch()
Launches the routing library and navigates to the route matching the current URL. Call this in your startup module.
go(n=0)
Moves by n entries relative to the current history position. Negative values go back; positive values go forward.
back()
Navigates back in the history stack.
forward()
Navigates forward in the history stack.
reload(hard=False)
Reloads the current page. If hard is True, the page will be reloaded from the server. If hard is False, the page will be removed from the cache and reloaded on the client.
add_event_handler(event_name, handler)
Adds an event handler for the given event name. The event handler should take a **event_args argument. The event_name can be one of the following:
  • "navigate": raised when the url changes.
  • "pending": raised when the navigation starts.
  • "idle": raised when the navigation is complete.
remove_event_handler(event_name, handler)
Removes an event handler for the given event name.
get_routing_context()
Returns the current routing context.
use_data(context_or_path_or_url=None, *, path=None, params=None, query=None, hash=None)
Loads and returns the data for the specified url/context (or for the specified path/params/query/hash). Returns the data (or raises if there is an error). If called with no arguments, uses the current navigation context.

Can be useful for routes that share data. Or layouts that need access to the data for the current route.

ensure_data(context_or_path_or_url=None, *, path=None, params=None, query=None, hash=None, data=..., stale=False)
Inserts data into the route cache for the specified url/context using that route's cache policy, then returns the same data. Routes with cache_data=NO_CACHE return the data without caching it. data is required. If stale=True, the cached entry is marked stale so stale-while-revalidate routes can return the cached data immediately and refresh it in the background.

The loader arguments passed to before_load, meta and load_data are path, params, query, deps, location, nav_context and form_properties. Read the URL fragment from location.hash; hash is not a separate argument to these methods. Client data loads also receive silent. RoutingContext.refetch(silent=...) also passes silent through as a loader arg, so custom loaders can decide whether to use silent/background fetches or visible loading indicators.

get_url()
get_url(*, path=None, params=None, query=None, hash=None, full=False)
get_url(path, **kws)
get_url(routing_context, **kws)
Gets the URL. If no keyword arguments are passed, the current URL will be returned. If full is True, the full URL will be returned (e.g., http://my-app.anvil.app/articles/123?foo=bar#hash). If full is False, the URL will be relative to the base URL (e.g., /articles/123?foo=bar#hash).
debug_logging(enable=True)
Enables or disables debug logging.
clear_cache()
Clears the cache of forms and data.
invalidate(*, path=None, deps=None, exact=False)
Invalidates any cached data and forms based on the path and deps. The exact argument determines whether to invalidate based on an exact match or a partial match.
open_form(form, **form_properties)
When migrating, you may be able to replace anvil.open_form with router.open_form. This will only work if you are not using params.
alert(content, *args, dismissible=True, **kwargs)
Shows an alert. If dismissible is True, the alert will be dismissed when the user navigates to a new page. To override Anvil's default alert, you can set the anvil.alert = router.alert.
confirm(content, *args, dismissible=False, **kwargs)
Shows a confirmation dialogue. The default dismissible=False blocks navigation while it is open. With dismissible=True, navigation closes the dialogue. To override Anvil's default confirmation dialogue, set anvil.confirm = router.confirm.
register_links(*dom_nodes, selector="a[href^='/']", active_class="active", active_callback=None, component=None)

Registers existing DOM links for client-side routing with active state tracking. Automatically detects if elements are <a> tags (registers directly) or containers (searches within using the selector). Use component to tie to a component's lifecycle (auto setup on page added, cleanup on page removed), or manually call the returned cleanup function. Useful for converting static HTML links to use the router without needing NavLink components.

Each link can specify exact matching behavior using data attributes (presence-based): - data-exact-path: Path must match exactly - data-exact-query: The link's query entries must match; extra current entries are allowed - data-exact-hash: Hash must match exactly

These attributes are read from each link element individually, allowing different links to have different exact matching behavior.

To skip active state tracking for a link (e.g., home page), use data-no-active: - data-no-active: Link will navigate but won't receive active state updates

See HTML link usage for a complete markup and Python example. Registration scans once and does not discover later DOM additions. Cleanup stops active-state tracking but leaves routing click handlers attached. Exclude external, download and target links from registration; the click handler does not check those attributes.

hooks.before_load(func)
Decorator to register a method as a before_load hook for a Route. Hooks are collected from all base classes and executed in reverse MRO order (base classes first, derived classes last). Each hook receives a nav_context keyword argument (the context dict accumulated so far), which can be read and updated for composable navigation logic.
from routing.router import Route, hooks, Redirect


class AuthenticatedRoute(Route):
    @hooks.before_load
    def require_user(self, nav_context, **loader_args):
        user = get_current_user()  # Application-defined helper
        if not user or not user.has_permission():
            raise Redirect(path="/login")
        return {"user": user}

Attach global hooks to the base class before defining route subclasses:

@hooks.before_load
def global_hook(self, nav_context, **loader_args):
    nav_context["feature_enabled"] = True


Route.global_hook = global_hook

Within one class, hooks currently run in reverse definition order. Keep dependent steps in a single hook. Overriding before_load bypasses these hooks unless the override calls super().before_load(**loader_args). See Navigation for composition examples.

Classes

Route
The base class for all routes.
RoutingContext
Provides information about the current route and navigation context. Passed to all forms instantiated by the routing library.
sorted_routes
A list of all registered routes, sorted in the order they will be matched. Useful for introspection, generating sitemaps, or custom navigation logic.

Components

routing.router.NavLink.NavLink
A link that you will likely use in your main layout's sidebar. Has an active property that is set when the NavLink's navigation properties match the current routing context.
routing.router.Anchor.Anchor
A link that you can use inline or as a container for other components.

Import component classes with from routing.router.NavLink import NavLink or from routing.router.Anchor import Anchor.

Context Managers

NavigationBlocker(warn_before_unload=False)
A context manager that will prevent the user from navigating away during the context.

Exceptions

Redirect
Raise during a route's before_load method to redirect to a different route.
NotFound
Raised when a route is not found for a given path.