Serve a static frontend build as low-priority routes. Use this for frontend tools that build static files into a directory, such as `dist`. **FastAPI** path operations are checked first, and the frontend files are checked only if no normal route matched. A
(
self,
path: Annotated[
str,
Doc(
"""
The URL path prefix where the frontend build should be served.
"""
),
],
*,
directory: Annotated[
str | os.PathLike[str],
Doc(
"""
The directory containing the static frontend build output.
"""
),
],
fallback: Annotated[
Literal["auto", "index.html", "404.html"] | None,
Doc(
"""
The fallback file behavior for missing frontend paths.
"""
),
] = "auto",
check_dir: Annotated[
bool,
Doc(
"""
Check that the frontend directory exists when the app is created.
"""
),
] = True,
)
| 2583 | self._mark_routes_changed() |
| 2584 | |
| 2585 | def frontend( |
| 2586 | self, |
| 2587 | path: Annotated[ |
| 2588 | str, |
| 2589 | Doc( |
| 2590 | """ |
| 2591 | The URL path prefix where the frontend build should be served. |
| 2592 | """ |
| 2593 | ), |
| 2594 | ], |
| 2595 | *, |
| 2596 | directory: Annotated[ |
| 2597 | str | os.PathLike[str], |
| 2598 | Doc( |
| 2599 | """ |
| 2600 | The directory containing the static frontend build output. |
| 2601 | """ |
| 2602 | ), |
| 2603 | ], |
| 2604 | fallback: Annotated[ |
| 2605 | Literal["auto", "index.html", "404.html"] | None, |
| 2606 | Doc( |
| 2607 | """ |
| 2608 | The fallback file behavior for missing frontend paths. |
| 2609 | """ |
| 2610 | ), |
| 2611 | ] = "auto", |
| 2612 | check_dir: Annotated[ |
| 2613 | bool, |
| 2614 | Doc( |
| 2615 | """ |
| 2616 | Check that the frontend directory exists when the app is created. |
| 2617 | """ |
| 2618 | ), |
| 2619 | ] = True, |
| 2620 | ) -> None: |
| 2621 | """ |
| 2622 | Serve a static frontend build as low-priority routes. |
| 2623 | |
| 2624 | Use this for frontend tools that build static files into a directory, |
| 2625 | such as `dist`. **FastAPI** path operations are checked first, and |
| 2626 | the frontend files are checked only if no normal route matched. |
| 2627 | |
| 2628 | A typical project could look like this: |
| 2629 | |
| 2630 | ```text |
| 2631 | . |
| 2632 | ├── pyproject.toml |
| 2633 | ├── app |
| 2634 | │ ├── __init__.py |
| 2635 | │ └── main.py |
| 2636 | └── dist |
| 2637 | ├── index.html |
| 2638 | └── assets |
| 2639 | └── app.js |
| 2640 | ``` |
| 2641 | |
| 2642 | Then in `app/main.py`: |