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.
Practice
Solution
Step 1: Understand Flask static file serving
Flask automatically serves files placed in thestaticfolder to the browser.Step 2: Identify correct folder for JavaScript files
JavaScript files must be inside thestaticfolder to be accessible via URL.Final Answer:
Inside the static folder -> Option AQuick Check:
Static folder = JavaScript files served [OK]
- Placing JS files in templates folder
- Putting JS files in root directory
- Expecting instance folder to serve static files
app.js located in the static folder inside your Flask HTML template?Solution
Step 1: Use correct HTML tag for JavaScript
The<script>tag with thesrcattribute is used to link JS files.Step 2: Use correct path to static folder
Flask serves static files under the/static/URL prefix, so path should be/static/app.js.Final Answer:
<script src="/static/app.js"></script> -> Option BQuick Check:
Script tag + /static path = correct link [OK]
- Using <link> instead of <script>
- Using href instead of src in <script>
- Linking to /templates folder
/static/script.js?
app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello'
Folder structure:
- static/
- script.js
- app.pySolution
Step 1: Understand Flask static file serving default behavior
Flask automatically serves files inside thestaticfolder at the URL path/static/filename.Step 2: Check if route conflicts with static path
The/route does not conflict with/static/script.js, so static file is served.Final Answer:
The file script.js will be served automatically -> Option DQuick Check:
Static folder files served automatically at /static/ [OK]
- Thinking Flask needs explicit route for static files
- Confusing root route with static file path
- Expecting 404 without static folder
@app.route('/js/app.js')
def serve_js():
return open('static/app.js').read()
But the browser shows the JavaScript code as plain text instead of running it. What is the problem?Solution
Step 1: Check how Flask serves static files
Flask sets the Content-Type header to 'application/javascript' automatically for static files.Step 2: Identify missing Content-Type in manual response
Returning raw file content without setting Content-Type causes browser to treat it as plain text.Final Answer:
The response is missing the correct Content-Type header for JavaScript -> Option AQuick Check:
Set Content-Type to application/javascript for JS files [OK]
- Not setting Content-Type header
- Assuming Flask auto-sets headers in manual routes
- Using wrong file path without checking
assets/js instead of the default static folder. Which Flask code snippet correctly serves these files at URL path /js/<filename>?Solution
Step 1: Use send_from_directory to serve files from custom folder
Flask'ssend_from_directorysafely serves files from any folder with correct headers.Step 2: Map URL path to custom folder
The route/js/<filename>callssend_from_directory('assets/js', filename)to serve files fromassets/js.Final Answer:
Use send_from_directory with assets/js folder -> Option CQuick Check:
send_from_directory + custom folder = correct serving [OK]
- Using send_file without setting headers
- Reading file content without headers
- Redirecting to static folder without files there
Ready to prove it?
Pass the test and this pattern moves unknown
