Skip to content

Fix FastAPI deep links with a router fallback - #4235

Merged
T4rk1n merged 4 commits into
plotly:devfrom
c0debeez:fix/fastapi-catchall-lifespan
Dec 3, 2026
Merged

T4rk1n merged 4 commits into
plotly:devfrom
c0debeez:fix/fastapi-catchall-lifespan

Conversation

@c0debeez

@c0debeez c0debeez commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4234.

Install the Dash index fallback as server.router.default during initialization. Explicit FastAPI routes take precedence, including routes added after startup. Mounted apps can serve deep links even when their lifespan never runs.

When several Dash apps share a server, the fallback tries the longest route prefix first and delegates unmatched requests to the host's original fallback. Each index uses the host's FastAPI route class so application dependencies and their overrides still apply. Rendering the index binds the request and the selected Dash app.

Tests

  • Cover repeated and disabled lifespans, a route added after startup, mounts with and without an inner prefix, and two Dash apps registered in either order.
  • Check HTTP methods, custom 404 handling, explicit route errors, host dependencies and overrides, and the app context used by a custom index.
  • Targeted backend tests on Dash 4.5.2 with the patched backend, FastAPI 0.165.0, and Starlette 1.10.0 yielded 42 passes and one existing Quart skip. Black, Flake8, and the backend Pylint check passed.

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

This fixes the duplicate route from #4234, but the catch-all still breaks in several related cases. They all come from registering a route during lifespan, so I'd block on changing the approach rather than adding more guards. If the catch-all is set at init as the router's not-found fallback (server.router.default), it no longer needs lifespan or a registered flag, and it runs after every route no matter when the route was added.

Here is what I tested locally, and it covers all the cases below:

def setup_catchall(self, dash_app: Dash):
    router = self.server.router
    dash_apps = getattr(router, "_dash_catchall_apps", None)
    if dash_apps is None:
        dash_apps = router._dash_catchall_apps = []
        fallback = router.default

        async def catchall(scope, receive, send):
            if scope["type"] == "http" and scope["method"] in ("GET", "HEAD"):
                path = _route_path(scope)  # root_path stripping from _is_dash_route
                for app in dash_apps:
                    if path.startswith(app.config.routes_pathname_prefix):
                        await _serve_index(app, scope, receive, send)
                        return
            await fallback(scope, receive, send)

        router.default = catchall

    dash_apps.append(dash_app)
    dash_apps.sort(key=lambda a: len(a.config.routes_pathname_prefix), reverse=True)

The lifespan handler then only runs dev tools and stream shutdown. Can you also update the changelog entry to cover the wider fix?

Comment thread dash/backends/_fastapi.py Outdated
try:
dash_app = get_app()
dash_app.backend._setup_catchall()
self.dash_server._setup_catchall(self.dash_app)

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.

This only runs when the server sends lifespan events. A Dash app mounted under a parent app (parent.mount("/dash", app.server)) never gets them, because Starlette doesn't forward lifespan to mounted apps. So /dash/reports returns 404 and Pages deep links break. The same happens with uvicorn --lifespan off or a TestClient used without with. Can you register the catch-all at init instead (see summary)?

Comment thread dash/backends/_fastapi.py Outdated
@@ -525,8 +527,7 @@ async def catchall(request: Request):

# pylint: disable=protected-access
self.add_url_rule("{path:path}", catchall, methods=["GET"])

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.

{path:path} is registered at the root, not under routes_pathname_prefix. With url_base_pathname="/app/", GET /other returns the Dash index instead of a 404. Flask and Quart go through dash_app._add_url, which adds the prefix. It also means two Dash apps on one server (/a/ and /b/) both get answered by whichever app registered first.

Comment thread dash/backends/_fastapi.py Outdated
def _setup_catchall(self):
try:
dash_app = get_app()
def _setup_catchall(self, dash_app: Dash):

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.

Since this is a route added at startup, any route added after startup is still hidden behind it: a GET to the new route returns the Dash index. Using the router's not-found fallback avoids that, and you can drop _catchall_registered and the lock.

assert f"<title>{app.title}</title>" in response.text


def test_fastapi_catchall_is_registered_once_after_custom_routes():

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.

Can you test behavior instead of counting {path:path} routes? Cases worth covering: lifespan re-entered, no lifespan, app mounted under a parent FastAPI, url_base_pathname with a 404 outside the prefix, a shared server with / and /a/, and a route added after startup. The retry test at line 50 can go once registration can't fail at startup.

@c0debeez c0debeez changed the title Fix FastAPI catch-all registration across lifespans Fix FastAPI deep links with a router fallback Dec 3, 2026
@c0debeez

c0debeez commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@T4rk1n, could you take another look at f1e11c8? I moved deep-link handling to server.router.default at initialization and removed the lifespan registration, lock, and retry logic.

Explicit host routes get the first chance to match. The fallback selects the most specific Dash prefix and runs the selected index through FastAPI so host dependencies and their overrides still apply.

The regression tests now check request behavior across repeated or disabled lifespans, mounted apps, shared servers, and routes added after startup. I also updated the changelog. The targeted backend run passed 42 tests with one existing Quart skip.

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

Fix is right, and it covers everything from my last review: no lifespan dependency, prefixes respected, late routes win, mounted apps work, and the tests check behavior now. I ran the backend tests on f1e11c8 and also tried a route added after startup, a custom router.default set before Dash, /app redirecting to /app/, and init_app on a separate server. All good. One small note inline about HEAD on the root index. It's not a blocker.

Comment thread dash/backends/_fastapi.py

# pylint: disable=protected-access
dash_app._add_url("", index, methods=["GET"])
dash_app._add_url("", _index_handler(dash_app), methods=["GET"])

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.

HEAD /reports now returns 200 through the fallback, but HEAD / still returns 405 because this route is GET only. Flask answers HEAD on both. _index_handler already handles HEAD, so can you add "HEAD" here too?

@sonarqubecloud

sonarqubecloud Bot commented Dec 3, 2026

Copy link
Copy Markdown

@T4rk1n
T4rk1n merged commit c25e077 into plotly:dev Dec 3, 2026
43 checks passed
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.

[BUG] FastAPI catch-all route is duplicated when lifespan restarts

2 participants