Part-2: Built-in Middleware in Django Framework

Altaf Khan
2 min readMay 14, 2024

Introduction

Django comes with several built-in middleware classes that provide various functionalities out-of-the- box. Here's a list of the built-in middleware

Security Middleware

This middleware adds several security enhancements to your Django application, such as setting security- related HTTP headers, protecting against clickjacking attacks, and ensuring that HTTP requests are redirected to HTTPS in production environments

Session Middleware

This middleware provides session management support for your Django application. It enables the use of Django's session framework, allowing you to store and retrieve session data for each user or anonymous users

Common Middleware

This middleware provides common HTTP features, such as URL redirection, URL normalization, and adding a trailing slash to URLs. It also handles conditional GET requests, ETags, and content compression

Csrf ViewMiddleware

Cross-Site Request Forgery (CSRF) protection middleware. This middleware adds CSRF tokens to outgoing HTML forms and verifies incoming requests to protect against CSRF attacks

AuthenticationMiddleware

This middleware adds the user attribute to the request object, representing the currently authenticated user. It enables Django's authentication system, allowing you to authenticate users and restrict access to certain views based on user authentication

MessageMiddleware

This middleware provides support for displaying messages (e.g., success messages, error messages) to users after a redirect. It allows views to set messages in the session, which are then displayed to the user on subsequent requests

XFrameOptionsMiddleware

This middleware sets the X-Frame- Options header to protect against clickjacking attacks. By default, it sets the header to 'DENY', but you can customize it to 'SAMEORIGIN' or 'ALLOW-FROM' as needed

LocaleMiddleware

This middleware enables language/ locale selection and activation based on the request. It sets the language for the current request based on the user's preferences (e.g., browser settings, session), allowing your application to serve localized content

Static Files Middleware

This middleware serves static files (e.g., CSS, JavaScript, images) during development. It intercepts requests for static files and serves them from the STATIC_ROOT directory specified in your settings

ConditionalGetMiddleware

This middleware handles conditional GET requests, allowing clients to make efficient use of cached responses by sending conditional headers (e.g., If-Modified-Since, If- None-Match) and checking if the content has changed since the last request

--

--

Altaf Khan

I'm Altaf khan, a passionate Python full-stack developer