Add Custom Headers in Response

A snippet showing how to add response headers using middleware.


# middleware.py

from django.conf import settings

class AddHeadersMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.extra_headers = getattr(settings, 'CUSTOM_RESPONSE_HEADERS', {})

    def __call__(self, request):
        response = self.get_response(request)
        # Set security headers (safe defaults) + any custom ones from settings
        response.setdefault('X-Content-Type-Options', 'nosniff')
        response.setdefault('X-Frame-Options', 'DENY')
        response.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin')
        for k, v in self.extra_headers.items():
            response[k] = v
        return response
  

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.AddHeadersMiddleware',
]

# Optional: project-wide custom headers (overridable per environment)
CUSTOM_RESPONSE_HEADERS = {
    'X-App-Version': '1.0.0',
    'Permissions-Policy': 'geolocation=(), microphone=()',
}
  

# views.py (any view)

from django.http import JsonResponse

def ping(request):
    return JsonResponse({'status': 'ok'})
  

# Test with curl

$ curl -i http://localhost:8000/ping/
HTTP/1.1 200 OK
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
X-App-Version: 1.0.0
Content-Type: application/json
...
{"status":"ok"}
  
Explanation:
  • Middleware sets headers on every response after your view runs, so the change is app‑wide.
  • We use response.setdefault() to avoid overwriting headers you might set per‑view.
  • Put environment‑specific headers in CUSTOM_RESPONSE_HEADERS for flexible configuration.
  • Common security headers included: X-Content-Type-Options, X-Frame-Options, and Referrer-Policy.
  • Category Middleware
  • Total Views 1041
  • Last Modified 06 April, 2026
  • Tags #middleware #headers #response #customization
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.