Middleware in web development

Middleware is a software that acts as a bridge between two different applications or components. In web application it sits between client and back end server. In web frameworks like Express.js or Django, middleware functions intercept incoming HTTP requests and can perform tasks such as authentication, security handling, data parsing, error handling, and more before passing the request to the next middleware function.

Middleware in Django:

In Django, all middleware classes should be listed in settings.py fille as a list. When a request is generated from client side, it will reach all middlewares in the settings one by one order wise. Finally it will reach the view function which will generate the response for request. And again the response will go through every middlewares in that list in reverse order. After passing through all middleware classes it will reach the client side. For easy understanding, Django middleware is like onion. Middlewares are the layers surrounded in onion. Request is a needle which will be inserted from one side of the onion and after reached the core, it will again piercing through the layers.

Default middlewares in Django:

In default middlewares, there will be __init__ , process_request and process_response functions. __init__ function in all middlewares will be executed when the server is started, process_request function will be executed when the request is generated from the client. And finally process_function will be executed after the request got response without any error. If any error occurs while processing the request, it will stop the remaining middlewares to be executed and process_exception function will be executed in reverse order.

Custom middlewares in Django:

We can add custom middlewares in Django if we need customarily check the data in the request or modify the response. As per Django documentation, custom middleware class should be created with functions such as __init__ and __call__. Here we can add the process_request and process_response functions if needed and we have to call the function manually inside the __call__ function.

0
Subscribe to my newsletter

Read articles from Varjinth subramaniyan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Varjinth subramaniyan
Varjinth subramaniyan