Place your CSS, JavaScript, and image files inside a folder named static/ next to your Flask application module (app.py), and generate their URLs inside Jinja2 templates using url_for('static', filename='css/style.css') rather than hardcoding /static/... paths—which automatically respects application prefixes, blueprints, and cache-busting query parameters while serving files from /static/<path:filename> out of the box during development.
Basic Example
my_flask_app/
├── app.py
├── templates/
│ └── index.html
└── static/
├── css/
│ └── style.css
├── js/
│ └── main.js
└── images/
└── logo.png
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
<!-- templates/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flask Static Assets</title>
<!-- 1. Recommended: Use `url_for('static', filename=...)` for CSS, JS, and images -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="App Logo">
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
Key Details & Edge Cases
- Always use forward slashes (
/) inurl_for('static', filename=...), even on Windows:filenameis a URL path relative tostatic/, not an OS filesystem path. Writingfilename='css\\style.css'breaks URL generation on Windows.
- Customizing the static folder path or URL prefix (
static_folder/static_url_path):- If your frontend assets live in a different directory (e.g.,
assets/or a React/Vitedist/build folder), configureFlask(__name__, static_folder="assets", static_url_path="/public"). Keep the endpoint name'static'inurl_for('static', filename=...)even when changingstatic_folderorstatic_url_path.
- If your frontend assets live in a different directory (e.g.,
- Blueprint-specific static files (
blueprint_name.static):- A Flask
Blueprintcan bundle its own isolated static assets (admin_bp = Blueprint("admin", __name__, static_folder="static", static_url_path="/admin/static")). Reference them in templates viaurl_for('admin.static', filename='admin.css').
- A Flask
- Serving files from a dynamic user-upload folder (
send_from_directory):- Never place untrusted user uploads inside
static/or serve arbitrary paths withsend_file(). Usesend_from_directory(app.config["UPLOAD_FOLDER"], filename), which safely blocks directory-traversal attacks (../etc/passwd).
- Never place untrusted user uploads inside
- Browser caching during development vs. production (
SEND_FILE_MAX_AGE_DEFAULT/ WhiteNoise):- During development, browsers may cache old CSS/JS files; hard-refresh (
Ctrl+Shift+R) or append a version query string (url_for('static', filename='css/style.css', v='1.2')). - In production behind Gunicorn / uWSGI, offload
/static/directly to Nginx / Caddy / a CDN for high throughput, or addWhiteNoise(app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/", prefix="static/")) when deploying self-contained PaaS containers without a separate reverse proxy.
- During development, browsers may cache old CSS/JS files; hard-refresh (
Comparison of Static File Serving Approaches in Flask
| Approach | Supports url_for() Reverse Routing? |
Directory Traversal Protection? | Production Throughput | Best Used When |
|---|---|---|---|---|
Built-in static/ + url_for('static', filename=...) (Recommended) |
Yes | Yes | Moderate (single-process WSGI) | Local development, internal tools, and small-to-medium Flask apps. |
Blueprint static_folder (url_for('bp.static', ...)) |
Yes | Yes | Moderate (single-process WSGI) | Modular apps where each Blueprint packages its own CSS/JS/images. |
send_from_directory(directory, filename) |
Yes (via your custom .route) |
Yes (blocks .. path traversal) |
Moderate | Serving user-uploaded files, generated reports, or protected downloads outside static/. |
Reverse Proxy (Nginx / Caddy) or WhiteNoise |
Yes (pairs seamlessly with url_for('static', ...)) |
Yes | High (zero Python worker overhead in Nginx) | Production deployments handling concurrent traffic, compression (gzip/brotli), and immutable cache headers. |
You must log in or register to comment.
