14. Managing CSS and JavaScript in Jinja2

Organizing Static Assets in FastAPI

FastAPI serves CSS and JavaScript through a dedicated static directory that is mounted explicitly in the application. This keeps frontend assets isolated from backend logic and templates. A predictable asset structure simplifies maintenance as the application grows.

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

Linking CSS and JavaScript in Jinja Templates

Jinja2 templates reference static assets using their mounted URLs. This avoids hard-coded filesystem paths and keeps templates declarative. Linking assets explicitly ensures consistent loading across environments.

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>

    {% block content %}{% endblock %}

    <script src="/static/js/app.js"></script>
</body>
</html>

CSS File Structure

CSS files define presentation rules and should remain independent of backend logic. Keeping styles in dedicated files improves reuse and avoids cluttering templates with inline styles.


JavaScript File Structure

JavaScript files handle client-side behavior and interactions. Separating scripts from templates allows frontend logic to evolve without modifying backend routes.


Maintaining Clean Separation Between Backend and Frontend

FastAPI routes focus on data preparation and orchestration, while templates handle structure and assets handle behavior and styling. This separation of concerns reduces coupling and supports scalable application development.

Last updated