In FastAPI 0.143, how does app.frontend() serve a single-page app's built dist folder, and why use it instead of mounting StaticFiles at the root?
answer
- path operations checked first
- deep links need a fallback
- Accept: text/html decides
- missing assets still 404
- check_dir="auto"
basics
~20 sIn FastAPI 0.143, app.frontend("/", directory="dist") serves the build only after every path operation fails to match, and returns index.html to browser navigations for client-side routes. A StaticFiles mount at / shadows later routes and 404s deep links.
solid answer
~40 s`app.frontend("/", directory="dist")`, added in FastAPI 0.138, serves the built files, but FastAPI checks path operations first wherever the call sits, so `/api/...` routes are never shadowed. With the default `fallback="auto"` it serves `404.html` with a `404` if the build has one; otherwise a `GET` or `HEAD` whose `Accept` header names `text/html` gets `index.html`, so a deep link such as `/dashboard/settings` reaches the client-side router. Missing assets still answer `404`. Mounting `StaticFiles(directory="dist", html=True)` at `/` has neither property: declared before the API routes it catches every path, and it answers deep links with `404`. `check_dir="auto"` fails app creation when `dist` is missing, except under `fastapi dev`. App, router and include-time dependencies also apply, so a frontend can sit behind cookie auth.
code
python · 10 linesfrom fastapi import FastAPI
app = FastAPI()
app.frontend("/", directory="dist")
@app.get("/api/health")
async def health() -> dict[str, bool]:
return {"ok": True}go deeper
Recall that app.frontend("/", directory="dist") serves a built frontend and that FastAPI's own path operations always take priority over it.
Explain fallback="auto": 404.html when present, otherwise index.html only for GET or HEAD navigations that accept HTML, and why missing assets still return 404.
Diagnose the classic bug where a StaticFiles mount at / declared early makes every API route answer 404, and explain how check_dir catches a deploy without its build.
Decide whether the API should serve the frontend at all, weighing one deployable and shared cookie auth against serving static files from separate infrastructure.
## The problem a single-page app poses A **single-page app** (SPA) is a frontend whose build step produces static files, usually an `index.html` plus hashed scripts and styles in a folder such as `dist`. Its pages are drawn in the browser by a **client-side router**, so a URL like `/dashboard/settings` is not a file on disk. When a user reloads that URL or opens it from a bookmark, the server receives the request directly and must answer with `index.html`, or the browser shows a `404`. At the same time, the backend's own paths, such as `/api/...`, must keep working, and a missing script must still be a `404` rather than an HTML page. ## Serving it with app.frontend() FastAPI 0.138 added `app.frontend()` and `router.frontend()` for exactly this case: ```python app.frontend("/", directory="dist") ``` Its rules, as FastAPI 0.143 implements them: - **Path operations win.** FastAPI tries every normal path operation first and consults the frontend only when none matched, regardless of where the `frontend()` call appears. The docs put it plainly: when a path operation also matches, the path operation wins. - **Real files are served as they are.** `/assets/app.js` serves `dist/assets/app.js`. - **`fallback="auto"` is the default.** If `dist/404.html` exists, a missing path gets that file with status `404`, which suits builds that pre-render one HTML file per page. Otherwise, if `dist/index.html` exists, a missing path gets `index.html` with `200`, but only for a `GET` or `HEAD` whose `Accept` header explicitly lists `text/html` or `application/xhtml+xml`, as a browser navigation does. - **Missing assets stay `404`.** A script, style or image request does not ask for HTML, so it never receives `index.html` with a `200`; it gets a `404`, with the `404.html` body when the build has one. - **Other methods get `404`.** A `POST` to a path that only the frontend matches answers `404`; a `POST` to a path that is an existing static file answers `405`. - **`fallback` can be set explicitly** to `"index.html"`, `"404.html"` or `None` (no fallback file at all). ## Why not StaticFiles at the root Before 0.138 a common recipe was `app.mount("/", StaticFiles(directory="dist", html=True))`. It has two defects for an SPA: | Behaviour | `StaticFiles` mount at `/` | `app.frontend("/", ...)` | |---|---|---| | Declared before `@app.get("/api/health")` | the mount matches first and `/api/health` answers `404` | the path operation still answers | | Deep link `/dashboard/settings` | `404` (or `404.html` if present) | `index.html` for browser navigations | | Missing `/assets/x.js` | `404` | `404` | | App, router and include dependencies | not applied (it is a separate app) | applied | A mount is matched in declaration order like any other route, so a mount at `/` declared early catches everything after it. Teams worked around this by declaring it last and writing their own fallback; `app.frontend()` makes both unnecessary. ## Checking the build directory `check_dir="auto"`, added in 0.141, is the default. If the `FASTAPI_ENV` environment variable is `development`, a missing directory only produces a warning, and `fastapi dev` sets that variable when it is unset, so the backend can start before the frontend is built. In any other environment a missing `dist` raises a `RuntimeError` when the app is created, which catches a deployment that forgot the build. `check_dir=True` always checks; `check_dir=False` skips the startup check when the files are produced later, and a request then fails if the directory is still missing. In practice the settings map to environments like this: - **Local development with `fastapi dev`:** the default only warns, so the API starts while the frontend build is still running. - **A built image or a production start:** the default raises, so a release without its `dist` folder fails at startup instead of serving `404` to every user. - **A build step that runs after the app object is created:** pass `check_dir=False` and rely on the request-time error. ## Dependencies, middleware and limits Frontend responses run inside the FastAPI app, so HTTP middleware applies, and since 0.139 dependencies from the app, from an `APIRouter` and from `include_router()` apply too. That allows, for example, putting a dashboard frontend behind the same cookie check as its API. With `router.frontend("/", directory="dist")` and `app.include_router(router, prefix="/app")` the frontend lives under `/app`. Two limits to keep in mind: 1. `app.frontend()` serves files that already exist; it does not render pages on the server. 2. A browser navigation to a mistyped API path, such as `/api/userz`, also receives `index.html`, because the fallback cannot tell an API typo from a client-side route. API clients that send `Accept: application/json` still get the normal `404`.
- In FastAPI 0.143, a browser user opens /api/userz by mistake and sees the SPA instead of a 404. Why, and does it affect API clients?With `fallback="auto"` and no `404.html`, `app.frontend()` returns `index.html` for any unmatched `GET` that explicitly accepts `text/html`, and it cannot tell an API typo from a client-side route. API clients that send `Accept: application/json` still get the normal `404`. To avoid it, serve the frontend under its own prefix with `router.frontend()` or let the SPA show its own not-found page.
- In FastAPI 0.143, the CI image build fails at import with a RuntimeError about the frontend directory. What happened?`check_dir="auto"` raises when the directory is missing unless `FASTAPI_ENV` is `development`, which `fastapi dev` sets. The image imported the app before the frontend build output was copied in. Copy `dist` first, or, if the files really are produced later, pass `check_dir=False` so the check moves to request time.
- A StaticFiles mount at / never interferes with API routes
- StaticFiles with html=True serves index.html for client-side routes
- app.frontend() must be declared after every API route
- The SPA fallback also answers missing JavaScript files with index.html
- app.frontend() renders pages on the server for each request
Assumes FastAPI 0.143: app.frontend() arrived in 0.138, dependencies on it in 0.139 and check_dir="auto" in 0.141; older releases only had StaticFiles.