← Back to Chapters

Built-in Middleware Classes

? Built-in Middleware Classes

? Quick Overview

Django provides a number of built-in middleware classes to handle common tasks like session management, authentication, and security. These middleware classes are automatically enabled when you start a new Django project, and they can be configured or replaced based on the needs of your project.

? Key Concepts

Built-in middleware classes are pre-configured middleware components provided by Django that handle common tasks in web applications. They allow you to easily add functionality to your Django application, such as handling user sessions, enforcing security policies, and managing cross-site request forgery (CSRF) protection.

? Syntax / Theory

Here are some of the most commonly used built-in middleware classes in Django:

  • SecurityMiddleware: Enforces security features like HSTS and clickjacking protection.
  • SessionMiddleware: Manages user sessions across requests.
  • AuthenticationMiddleware: Attaches authenticated users to requests.
  • CsrfViewMiddleware: Protects against CSRF attacks.
  • CommonMiddleware: Handles redirects and common HTTP behaviors.
  • LocaleMiddleware: Determines user language preferences.
  • RedirectFallbackMiddleware: Redirects unmatched URLs.

? Code Example(s)

? View Code Example
# settings.py - Default middleware configuration
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

? Live Output / Explanation

Each middleware runs in the order defined in the MIDDLEWARE list. This order is critical because some middleware depends on others. For example, security checks must occur before sessions and authentication logic.

? Interactive Example

Use the simulator below to visualize how a request travels through the middleware "onion". Toggle middleware on/off to see how the chain changes.

Ready to simulate...

? Use Cases

  • Global request and response modification
  • Application-wide authentication handling
  • Security enforcement such as HTTPS and CSRF protection
  • Localization and language detection

✅ Tips & Best Practices

  • Maintain correct middleware order for proper execution.
  • Use middleware for cross-cutting concerns like logging and security.
  • Test middleware behavior in development and production environments.

? Try It Yourself / Practice Tasks

  • Add or remove middleware and observe behavior changes.
  • Enable HTTPS enforcement and test redirection.
  • Submit forms without CSRF tokens and inspect Django’s response.