Performance: Why middleware filters requests
Middleware filtering affects the time before the main content loads by controlling which requests proceed, impacting server response time and perceived page speed.
<?php
// In middleware
public function handle($request, Closure $next) {
if (!$request->user()->isAdmin()) {
abort(403);
}
return $next($request);
}<?php
// In controller method
public function index(Request $request) {
if (!$request->user()->isAdmin()) {
abort(403);
}
// heavy data processing here
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Late authorization in controller | N/A | N/A | N/A | [X] Bad |
| Early authorization in middleware | N/A | N/A | N/A | [OK] Good |
public function handle($request, Closure $next) {
if (!$request->hasHeader('token')) {
return response('Unauthorized', 401);
}
return $next($request);
}public function handle($request, Closure $next) {
if ($request->header('X-API-KEY') == null) {
$next($request);
}
return response('Forbidden', 403);
}Pass the test and this pattern moves unknown