We serve JavaScript files so web pages can use scripts to add interactivity and dynamic features.
Serving JavaScript files in Flask
from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/js/<path:filename>') def serve_js(filename): return send_from_directory('static/js', filename) if __name__ == '__main__': app.run()
JavaScript files are usually placed in a folder like static/js.
The send_from_directory function sends the file to the browser safely.
static/js folder when requested via /js/filename.js.from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/js/<path:filename>') def serve_js(filename): return send_from_directory('static/js', filename)
static folder without extra routes.from flask import Flask app = Flask(__name__, static_url_path='/static') # Flask automatically serves files from 'static' folder if __name__ == '__main__': app.run()
This Flask app serves an HTML page with a button. The JavaScript file script.js is served from static/js folder and adds a message when the button is clicked.
from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/') def index(): return '''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Serve JS Example</title> <script src="/js/script.js"></script> </head> <body> <h1>Click the button</h1> <button onclick="showMessage()">Click me</button> <p id="message"></p> </body> </html>''' @app.route('/js/<path:filename>') def serve_js(filename): return send_from_directory('static/js', filename) if __name__ == '__main__': app.run(debug=True)
Put your JavaScript files inside the static/js folder to keep things organized.
Flask automatically serves files from the static folder, so you can also link scripts with /static/js/script.js without extra routes.
Use browser developer tools (F12) to check if your JavaScript file loads correctly and to debug any errors.
Serving JavaScript files lets your web pages run scripts for interactivity.
Place JavaScript files in a static folder and use Flask routes or default static serving to deliver them.
Link JavaScript files in your HTML with <script src="..."></script> tags.