Skip to content

Flask - Static Files

Web applications typically need to serve static files like CSS stylesheets, JavaScript code, images, and fonts. Flask is designed to handle this easily during development.

By default, Flask looks for static files in a folder named static located in your application’s root directory (the same directory as your main Python script or package). These files will be accessible under the /static URL path.

To link to static files within your templates, use the special url_for() function with the endpoint name ‘static’. You also provide the filename argument, which is the path to the file relative to the static folder.

/your_project
app.py
/static
style.css
/js
main.js
/templates
index.html

Let’s create a simple Flask app (app.py) that renders an HTML template (templates/index.html). The HTML will include a button that triggers a JavaScript function defined in static/js/main.js.

from flask import Flask, render_template
app = Flask(__name__) # Creates the Flask application instance
@app.route('/')
def index():
# Renders the index.html template
return render_template('index.html')
if __name__ == '__main__':
# Runs the development server
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>Static Files Example</title>
<!-- Link to the JavaScript file using url_for -->
<script type="text/javascript"
src="{{ url_for('static', filename='js/main.js') }}"></script>
<!-- You could similarly link CSS: -->
<!-- <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> -->
</head>
<body>
<h1>Flask Static Files</h1>
<p>Click the button below!</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
function sayHello() {
// Display a simple alert box (often used for basic debugging)
alert("Hello from your static JavaScript file!");
}

When you run app.py and navigate to / in your browser, Flask will render index.html. The browser will then request /static/js/main.js, which Flask will serve from your project’s static/js/ directory. Clicking the button will execute the sayHello() function.

Note: While Flask’s development server can serve static files, it’s generally recommended to configure your production web server (like Nginx or Apache) to handle serving static files directly for better performance.