Table Of Contents
Problem
You need to add custom headers (like API version, rate limit info, or security headers) to every API response in your Laravel application.
Solution
Create a middleware that adds headers to the response:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AddApiHeaders
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
// Add custom headers
$response->headers->set('X-API-Version', '1.0');
$response->headers->set('X-Response-Time', round(microtime(true) - LARAVEL_START, 3));
$response->headers->set('X-RateLimit-Limit', '60');
$response->headers->set('X-RateLimit-Remaining', '59');
return $response;
}
}
Register the middleware in app/Http/Kernel.php
:
protected $middlewareGroups = [
'api' => [
// ... other middleware
\App\Http\Middleware\AddApiHeaders::class,
],
];
Why It Works
Middleware intercepts the request/response cycle. By applying it after the response is generated ($next($request)
), you can modify headers before they're sent to the client. The middleware automatically applies to all routes in the api
middleware group.
For specific routes only, register as route middleware:
// In Kernel.php
protected $routeMiddleware = [
'api.headers' => \App\Http\Middleware\AddApiHeaders::class,
];
// In routes/api.php
Route::middleware(['api.headers'])->group(function () {
// Your API routes
});
Middleware runs on every matching request, so keep it lightweight. For complex header logic, consider using service providers or response macros. Always test your middleware thoroughly, especially when dealing with CORS headers or authentication headers.
Related: Laravel API Development: Best Practices and Security | Implementing API Versioning in Laravel: Multiple Strategies | Laravel API Rate Limiting: Protect Your Endpoints from Abuse
Add Comment
No comments yet. Be the first to comment!