Middleware is a powerful concept in web applications that allows you to process requests and responses before they reach the main application logic. In Flask, middleware functions sit between the client request and the final response, enabling tasks like logging, authentication, request modifications, and more.
Flask applications generally uses middleware's in:
- Authentication & Authorization: Checking user authentication before processing a request.
- Logging & Monitoring: Capturing request details for debugging and analytics.
- Request Validation: Ensuring requests meet certain criteria before reaching the main app.
- Response Modification: Adding or modifying headers before sending a response.
- Rate Limiting & Security: Controlling request rates and preventing malicious activities.
Let's explore several ways to implement middleware in Flask applications.
Creating Custom Middleware in Flask
Flask provides hooks, which are special functions that allow you to execute code before or after processing a request. These hooks help in modifying requests, logging, authentication, and more. Two commonly used hooks for middleware are:
- before_request : Runs before the request is processed.
- after_request : Runs after the request is processed, modifying the response if needed.
A simple way to implement middleware in Flask is by using these hooks.
Python
from flask import Flask, request
app = Flask(__name__)
@app.before_request
def log_request():
print(f"Incoming request: {request.method} {request.url}")
@app.after_request
def log_response(response):
print(f"Outgoing response: {response.status_code}")
return response
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Explanation:
1. @app.before_request: Middleware that handels incoming requests ()
- log_request(): Runs before each request.
- Prints the HTTP method and request URL.
2. @app.after_request: Middleware that handles outgoing responses ()
- log_response(response)- Runs after each request.
- Logs the response status code.
- Returns response to complete the request cycle.
Output:
Middleware OutputNotice that every time we refresh the Flask app, the terminal displays "Outgoing response: 200" because of the middleware. This demonstrates how middleware can handle tasks before reaching the main logic.
Middleware for Authentication and Authorization
Authentication middleware ensures that only authorized users can access specific routes. This is useful for securing APIs and web applications. Let's create a simple flask app and implement middleware for authentication and authorization in it.
Python
from flask import Flask, request, jsonify
app = Flask(__name__)
API_KEY = "my_secret_api_key"
@app.before_request
def check_authentication():
token = request.headers.get("Authorization")
if token != f"Bearer {API_KEY}":
return jsonify({"error": "Unauthorized"}), 401
@app.route('/protected')
def protected():
return jsonify({"message": "Welcome to the protected route!"})
if __name__ == '__main__':
app.run(debug=True)
Explanation:
1. before_request Middleware:
- Extracts the Authorization token from request headers.
- If the token is missing or incorrect, returns 401 Unauthorized.
2. /protected - route that can only be accessed if a valid token is provided.
Output:
We can test the application using Postman API, below is snapshot of response when a GET request is made to the /protected route with providing the header.
Response without authentication tokenNotice that when the GET request is made to the route with the authentication token, we get a 200 OK status response. Below is the snapshot.
Response with authentication tokenThird-Party Middleware in Flask
Instead of writing custom middleware for every feature, we can use Flask extensions or third-party libraries for advanced middleware functionalities. Some commonly used middleware libraries include:
- Flask-CORS – Handles Cross-Origin Resource Sharing (CORS).
- Flask-Limiter – Implements rate limiting to prevent abuse.
- Flask-Talisman – Adds security headers for better protection.
Let's create a flask app using CORS.
What is CORS
CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers that restricts how resources on a web page can be requested from another domain.
For example, if your frontend (React, Vue, or plain JavaScript) is running on http://localhost:3000 and your Flask backend is running on http://127.0.0.1:5000, the browser will block requests from the frontend to the backend due to CORS policy. CORS middleware allows controlled access to your Flask API from different origins.
To use any third party middleware in our application, we are required to install its module in our environment, use this command in terminal to install flask-cors
pip install flask-cors
After installing the flask-core module, create the file app.py an paste the code below.
Python
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
# Allow requests only from specific frontend origins
CORS(app, origins=["http://localhost:3000", "https://myfrontend.com"])
@app.route('/public-data')
def public_data():
return jsonify({"message": "This data is accessible from allowed origins."})
@app.route('/private-data')
def private_data():
return jsonify({"message": "This endpoint also follows CORS rules."})
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- CORS(app, origins=["http://localhost:3000"]) allows only http://localhost:3000 and https://myfrontend.com to make API requests.
- It enables CORS for all routes but only for allowed domains.
- If a request comes from an unlisted domain, the browser will block it.
Using Multiple Middleware Layers
In Flask, wecan apply multiple middleware functions to process requests before they reach the route handler. This is useful when we need to enforce multiple layers of checks, such as logging, authentication, validation, or security policies. By chaining middleware, we can ensure structured request handling without duplicating logic inside individual route functions.
Let's create a flask app that demonstrate using multiple middleware.
Python
from flask import Flask, request, jsonify
app = Flask(__name__)
API_KEY = "my_secret_api_key"
@app.before_request
def log_request():
""" Logs incoming request details. """
print(f"Incoming request: {request.method} {request.url}")
@app.before_request
def check_authentication():
""" Checks if the request has a valid authentication token. """
token = request.headers.get("Authorization")
if token != f"Bearer {API_KEY}":
return jsonify({"error": "Unauthorized"}), 401 # Block unauthorized requests
@app.after_request
def log_response(response):
""" Logs outgoing response details. """
print(f"Outgoing response: {response.status_code}")
return response # Must return the response object
@app.route('/secure-data')
def secure_data():
return jsonify({"message": "Access granted to secure data."})
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- Logging Middleware (before_request):
- Logs the HTTP method and URL of every incoming request.
- Helps in debugging and monitoring request flow.
- Authentication Middleware (before_request):
- Extracts the Authorization token from the request headers.
- Blocks access (401 Unauthorized) if the token is missing or incorrect.
- Response Logging Middleware (after_request):
- Logs the response status code before sending it to the client.
- Ensures tracking of both incoming and outgoing traffic.
Output:
Allowed Request (Valid Token)
Status OKBlocked Request (No Token)
Status - Unauthorized Without TokenBlocked Request (Invalid Token)
Request logs
Similar Reads
Flask WSGI Middleware When building Flask applications, middleware helps modify requests and responses before they reach the application or the client. Flask itself supports middleware using hooks like before_request and after_request, but WSGI (Web Server Gateway Interface) middleware works at a lower level. It sits bet
3 min read
Flask - Templates In this article, we are going to learn about the flask templates in Python. Python is a high-level, open-source, object-oriented language, consisting of libraries, used in many domains, such as Web Development, Machine Learning, and so on. In web development, Python is used for building REST APIs, s
8 min read
Middleware in Django Middleware is a series of processing layers present between the web server and the view (controller in some frameworks), allowing the user to intercept, modify, and add behavior to these requests and responses.What is Middleware in Django?In Python Django, middleware is a framework that provides a m
9 min read
Python Falcon - Middleware Middleware in Falcon is a powerful mechanism that allows you to preprocess requests and post-process responses globally across your application. It acts as a bridge between incoming and outgoing requests, allowing you to perform authentication, logging, and request/response modification tasks. What
5 min read
Flask Web Sockets WebSockets enable real-time, bidirectional communication between a client and a server. Unlike traditional HTTP requests, which follow a request-response cycle, WebSockets maintain a persistent connection, allowing instant data exchange. This is particularly useful for applications like:Live chat.No
4 min read