Core Architecture - Middleware

Middleware is a core architectural concept that sits between the incoming HTTP request and the final response. It allows Drupal to inspect, modify, or short circuit requests and responses before they reach controllers or after they leave them.

Starting with Drupal 8, Drupal adopted Symfony’s HTTP Kernel stack, which introduced middleware as a first class concept. Middleware plays a critical role in request handling, security, performance, and system wide behavior.

The goal is to understand middleware as part of Drupal’s request pipeline, not just how to write one.

Why Middleware Belongs in Core Architecture

Middleware operates at a very low level in the request lifecycle.

Drupal core uses middleware to:

  • Handle reverse proxy and trusted headers
  • Manage session handling
  • Enforce page caching
  • Process authentication
  • Integrate with HTTP cache systems

Middleware affects every request, regardless of route, controller, or module.

What Is Middleware

Middleware is a component that:

  • Receives an HTTP request
  • Can modify or replace the request
  • Can stop further processing
  • Can modify or replace the response

Middleware wraps the application logic rather than being part of it.

Middleware in the Request Lifecycle

High level flow:

  1. HTTP request enters Drupal
  2. Middleware stack executes in order
  3. Request reaches routing and controller
  4. Response is generated
  5. Middleware stack executes on the way back
  6. Final response is sent

Middleware runs both before and after controller execution.

Drupal Middleware Stack

Drupal builds a middleware stack during container compilation.

Core middleware examples:

  • PageCache
  • DynamicPageCache
  • Session
  • ReverseProxy
  • Negotiation

These middleware components are services tagged and ordered deliberately.

Symfony vs Drupal Middleware

Drupal uses Symfony’s HttpKernelInterface but adds its own middleware layer.

Key points:

  • Symfony provides the kernel contract
  • Drupal assembles the middleware stack
  • Middleware order is critical

Drupal middleware is not the same as PSR-15 middleware.

Writing a Custom Middleware

Middleware Interface

Drupal middleware implements HttpKernelInterface.

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ExampleMiddleware implements HttpKernelInterface {

  protected HttpKernelInterface $httpKernel;

  public function __construct(HttpKernelInterface $httpKernel) {
    $this->httpKernel = $httpKernel;
  }

  public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = TRUE): Response {
    // Before controller

    $response = $this->httpKernel->handle($request, $type, $catch);

    // After controller

    return $response;
  }
}

Registering Middleware

Middleware must be registered as a service and tagged.

services:
  my_module.example_middleware:
    class: Drupal\my_module\Middleware\ExampleMiddleware
    tags:
      - { name: http_middleware, priority: 200 }

Priority controls execution order.

Middleware Priority

Middleware executes in priority order.

  • Higher priority runs earlier on request
  • Lower priority runs later

Incorrect priority can break caching or authentication.

Middleware vs Event Subscribers

Middleware:

  • Wraps the entire request lifecycle
  • Executes before routing
  • Executes after response creation

Event subscribers:

  • React to specific events
  • Execute at defined lifecycle points
  • Do not wrap execution

Middleware is more invasive and should be used sparingly.

Middleware vs Controllers

Controllers:

  • Handle matched routes
  • Return content

Middleware:

  • Handles all requests
  • Is route agnostic

Controllers should never replace middleware logic.

Common Use Cases

  • Request rewriting
  • Header manipulation
  • Early redirects
  • Security enforcement
  • Request logging

Middleware is ideal for cross application concerns.

Common Mistakes

  • Using middleware for business logic
  • Incorrect middleware priority
  • Duplicating event subscriber behavior
  • Modifying responses without cache awareness

Middleware mistakes affect the entire site.

Drupal 10 and 11 Best Practices

  • Use middleware only when necessary
  • Prefer event subscribers for most extensions
  • Keep middleware small and focused
  • Be careful with priority values
  • Understand cache implications

How Middleware Fits with Other Core Systems

Middleware integrates closely with:

  • HTTP Kernel
  • Routing system
  • Event dispatcher
  • Cache system
  • Authentication

Middleware operates before most other systems.

Acquia Exam Notes and Cheat Sheet

Key concepts to remember:

  • Middleware wraps request and response
  • It executes before routing
  • It is registered as a service
  • Priority determines execution order
  • Middleware affects all routes

Common exam traps:

  • Confusing middleware with event subscribers
  • Thinking middleware replaces controllers
  • Ignoring cache and security impact
  • Using middleware for entity logic

Quick decision guide:

  • Need to intercept all requests: middleware
  • Need to react to lifecycle event: subscriber
  • Need route specific logic: controller

If the question mentions request wrapping or early interception, middleware is the answer.

Summary

Middleware is a low level architectural layer that wraps Drupal’s entire request lifecycle. It enables powerful system wide behavior but must be used carefully. Understanding middleware is essential for working with Drupal’s HTTP stack and for advanced architecture and Acquia certification success.

This article prepares you for deeper topics such as cache middleware ordering, reverse proxy integration, and HTTP kernel internals.