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.
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.
Here are some of the most commonly used built-in middleware classes in Django:
# 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',
]
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.
Use the simulator below to visualize how a request travels through the middleware "onion". Toggle middleware on/off to see how the chain changes.