Using CakePHP 4 Middleware for Request Logging and Authentication
Learn how CakePHP 4’s middleware system lets you centralize logging, authentication, and other cross‑cutting concerns, keeping controllers focused on business logic.
08 Sept 2026, 08:17 UTC

Problem: Cross‑cutting concerns clutter controllers
In a typical CakePHP application, controllers often end up with repetitive code for tasks such as logging request details, checking authentication, or setting response headers. This duplication makes the business logic harder to read and increases the chance of inconsistencies when the same concern needs to be tweaked across multiple actions.
Thesis: CakePHP 4 middleware centralizes cross‑cutting concerns
CakePHP 4 provides a PSR‑15 compliant middleware system that lets you insert reusable layers before and after the controller action. By moving concerns like logging or authentication into middleware, controllers stay focused on domain logic while the framework guarantees a predictable execution order.
Understanding Middleware in CakePHP 4
Middleware classes implement Psr\Http\Server\MiddlewareInterface and define a process($request, $handler) method. The method receives the incoming request, a handler that represents the next layer, and must return a response. Anything done before calling $handler->handle($request) runs on the way in; anything after runs on the way back.
Implementing a Custom Logging Middleware
Below is a simple middleware that logs the request method and URL to a file. Place it in src/Middleware/LogMiddleware.php.
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
class LogMiddleware implements MiddlewareInterface
{
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): \Psr\Http\Message\ResponseInterface
{
$this->logger->info(
sprintf('{method} {uri}', $request->getMethod(), $request->getUri())
);
return $handler->handle($request);
}
}
?>
Assuming you have configured a Monolog logger in your container, the middleware will receive it via dependency injection.
Configuring the Middleware Queue
Register the middleware in src/Application.php inside the middleware() method. The order you add items determines execution order.
<?php
namespace App;
use Cake\Http\BaseApplication;
use App\Middleware\LogMiddleware;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class Application extends BaseApplication
{
public function middleware($queue)
{
// Create a simple logger that writes to logs/app.log
$log = new Logger('app');
$log->pushHandler(new StreamHandler(LOGS . 'app.log'));
// Add logging middleware first, then framework‑provided ones
$queue->add(new LogMiddleware($log));
$queue->add(new \Cake\Middleware\CsrfProtectionMiddleware());
$queue->add(new \Authentication\Middleware\AuthenticationMiddleware());
return $queue;
}
}
?>
With this setup, every request passes through LogMiddleware before CSRF and authentication layers.
Trade‑off: Performance and Order Sensitivity
While middleware keeps code clean, each added layer incurs a small overhead. Heavy work (e.g., complex database queries) inside middleware can increase latency noticeably. Profiling with tools like xdebug or CakePHP’s built‑in DebugKit panel helps verify that the added time stays within acceptable bounds.
More critically, the order of middleware matters. Placing authentication after CSRF protection could cause the CSRF token to be validated on unauthenticated requests, leading to false positives. Always test the queue with a few representative routes to confirm behavior.
Actionable Closing
Start by identifying a cross‑cutting concern that repeats across controllers—logging is a safe first step. Implement a minimal middleware class, add it to the queue, and verify the log file grows as expected. Once comfortable, extract other concerns (authentication, locale detection, input sanitization) into their own middleware, keeping the controller layer lean and the application easier to maintain.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.