0
0
Flaskframework~5 mins

Serving JavaScript files in Flask

Choose your learning style9 modes available
Introduction

We serve JavaScript files so web pages can use scripts to add interactivity and dynamic features.

You want to add buttons that do things without reloading the page.
You need to run code in the browser to update content dynamically.
You want to separate your JavaScript code from HTML for cleaner structure.
You want to reuse the same JavaScript file on multiple pages.
You want the browser to cache JavaScript files for faster loading.
Syntax
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.

Examples
This example serves JavaScript files from static/js folder when requested via /js/filename.js.
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)
Flask can serve static files automatically from the static folder without extra routes.
Flask
from flask import Flask

app = Flask(__name__, static_url_path='/static')

# Flask automatically serves files from 'static' folder

if __name__ == '__main__':
    app.run()
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.