# Middleware

Whereas listeners allow you to attach functionality to the lifecycle of a worker process, middleware allows you to attach functionality to the lifecycle of an HTTP stream.

You can execute middleware either before the handler is executed, or after.

# Attaching middleware

This should probably look familiar by now. All you need to do is declare when you would like the middleware to execute: on the request or on the response.

async def extract_user(request):
    request.ctx.user = await extract_user_from_request(request)
app.register_middleware(extract_user, "request")

Again, the Sanic app instance also has a convenience decorator.

async def extract_user(request):
    request.ctx.user = await extract_user_from_request(request)

Response middleware receives both the request and response arguments.

async def prevent_xss(request, response):
    response.headers["x-xss-protection"] = "1; mode=block"

You can shorten the decorator even further. This is helpful if you have an IDE with autocomplete.

This is the preferred usage, and is what we will use going forward.

async def extract_user(request):
async def prevent_xss(request, response):

# Modification

Middleware can modify the request or response parameter it is given, as long as it does not return it.

# Order of execution

  1. Request middleware: add_key
  2. Route handler: index
  3. Response middleware: prevent_xss
  4. Response middleware: custom_banner
async def add_key(request):
    # Arbitrary data may be stored in request context:
    request.ctx.foo = "bar"
async def custom_banner(request, response):
    response.headers["Server"] = "Fake-Server"
async def prevent_xss(request, response):
    response.headers["x-xss-protection"] = "1; mode=block"
async def index(request):
    return text(request.ctx.foo)

You can modify the request.match_info. A useful feature that could be used, for example, in middleware to convert a-slug to a_slug.

def convert_slug_to_underscore(request: Request):
    request.match_info["slug"] = request.match_info["slug"].replace("-", "_")
async def handler(request, slug):
    return text(slug)
$ curl localhost:9999/foo-bar-baz

# Responding early

If middleware returns a HTTPResponse object, the request will stop processing and the response will be returned. If this occurs to a request before the route handler is reached, the handler will not be called. Returning a response will also prevent any further middleware from running.


You can return a None value to stop the execution of the middleware handler to allow the request to process as normal. This can be useful when using early return to avoid processing requests inside of that middleware handler.

async def halt_request(request):
    return text("I halted the request")
async def halt_response(request, response):
    return text("I halted the response")

# Order of execution

Request middleware is executed in the order declared. Response middleware is executed in reverse order.

Given the following setup, we should expect to see this in the console.

async def middleware_1(request):
async def middleware_2(request):
async def middleware_3(request, response):
async def middleware_4(request, response):
async def handler(request):
    print("~ handler ~")
    return text("Done.")
~ handler ~
[INFO][]: GET http://localhost:8000/handler  200 5

# Middleware priority

You can modify the order of execution of middleware by assigning it a higher priority. This happens inside of the middleware definition. The higher the value, the earlier it will execute relative to other middleware. The default priority for middleware is 0.

async def low_priority(request):
async def high_priority(request):

Added in v22.9

MIT Licensed
Copyright © 2018-present Sanic Community Organization

~ Made with ❤️ and ☕️ ~