Types of Middleware in Django
Django’s middleware can be divided into 2 types: built-in and custom.
Built-in Django Middleware: Django comes with a set of built-in middleware classes. These are some of the most commonly used default middleware classes in Django:
- SecurityMiddleware: It provides several security-related features such as ensuring that all HTTP requests are redirected to HTTPS and is used to add security headers to responses.
- SessionMiddleware: It helps in managing sessions for users. It enables Django to handle session data, making it available to views and templates.
- CommonMiddleware: Handles common operations such as URL redirection (adding/removing “www” prefix), appending slashes to URLs.
- CsrfViewMiddleware: Enables protection against Cross-Site Request Forgery (CSRF) attacks. It adds and verifies a CSRF token in POST requests to protect against malicious requests from other sites.
- AuthenticationMiddleware: Adds the ‘
user'
attribute to the request, representing the currently logged-in user, if applicable. It also manages the user’s session and authentication state.
Custom Middleware: These are the middleware that a user creates for their purpose. It can be built as a class-based style with a call method that processes requests and responses or as a function style that accepts a get_response callable. It is produced in the middleware.py file. A middleware is turned on by including it in the Django settings’ MIDDLEWARE list.
Middleware in Django [image, Video error]
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.