Search code examples
pythondjangodjango-rest-frameworkcache-controlx-frame-options

Django DRF best practices to return response headers on every request


I am using Django DRF.

What is the best way to add the below response headers as part of every request

Cache-control: no-store, max-age=0

Pragma: no-cache 

Strict-Transport-Security: max-age=7776000; includeSubDomains

X-XSS-Protection: 1; mode=block

X-Content-Type-Options: nosniff

X-Frame-Options: DENY

Ideally I want to configure this in one place.


Solution

  • From DRF documentation:

    Signature: Response(data, status=None, template_name=None, headers=None, content_type=None)

    headers: A dictionary of HTTP headers to use in the response.

    So just use it like this:

    def foo(request):
        # logic
        headers = {
            'Cache-control': 'no-store, max-age=0',
            # ...
            'X-Frame-Options': 'DENY'
        }
        return Response(your_data, headers)
    

    If you want it on every request just create your custom Response class:

    CustomResponse(Response):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.headers= {
                'Cache-control': 'no-store, max-age=0',
                # ...
                'X-Frame-Options': 'DENY'
            }
    

    Or, another solution, maybe more simple, create a global headers variable and use it in your Response object.