How to Create a Custom Middleware in Django?

Programming
Published in Blog on April 09, 2025 3 min read
Custom Middleware in Django Banner Image



Middleware is one of Django’s most powerful features. It lets you hook into Django’s request/response cycle and perform actions globally across your project. In this blog post, we’ll explore how to create and use a custom middleware in Django, with practical code examples.

 


What is Middleware in Django?

Middleware is a lightweight plugin that processes requests and responses globally. It comes between the request and view (or view and response) and can be utilized to:

  • Modify the request before it gets to the view.

     
  • Modify the response before it gets to the browser.

     
  • Handle exceptions globally.

     
  • Add headers or logging, etc.

     

 


Basic Middleware Structure

In Django, a middleware is just a class that defines one or more of the following methods:

 



 

“Let’s build one step by step”

 


Example: Custom Middleware to Log Request Time

Goal

We want to log the time spent processing every request using a custom middleware.

 

Step 1: Create the Middleware File

Inside your Django app, create a file named middleware.py (if it doesn’t already exist):





 

Step 2: Add Middleware Code







 

Step 3: Add It to settings.py

Open your settings.py file and add your custom middleware to the MIDDLEWARE list:



 

Make sure you place it after SecurityMiddleware but before the view-related ones if needed.

 

Step 4: Test It

Run your Django server:

 

Now visit any URL in your app. You should see logs like this in your terminal:



 

 




 

Custom Use Case Ideas

You can modify this middleware for different use cases:

  • Block IPs or log IP addresses

     
  • Add custom headers

     
  • Modify response body (e.g., wrap HTML)

     
  • Log user agents or referrers

     
  • Automatically compress large responses

     

 


Tips & Best Practices

  • Keep middleware lightweight and fast—don’t do heavy lifting here.

     
  • Use middleware for global tasks, not per-view logic.

     
  • Log or modify data that doesn't need view-specific context.

     

 


Bonus: Middleware with Exception Handling

Want to catch and log exceptions? Add this method to your middleware:



 

 


Conclusion

Middleware gives you powerful control over your Django app’s request-response flow. With a custom middleware, you can log information, transform requests/responses, and catch exceptions at the global level.

Now that you’ve built one yourself, try exploring advanced ideas like authentication checks, rate limiting, or response formatting through middleware!

Hi...

Got ideas? We’ve got
the skills. Let’s team up.

Have a question or ready to discuss your project? Our team is here to help you scope, design, and deliver.

Trusted by Leading Businesses
Metro
Zabeel Equstrian
GEMS Logo
APSG Logo
Anisia Logo
Foodlinx Logo
🌐 +1
Select Subject?
send mail graphic