I have a Laravel application deployed to AWS via Vapor. I need one of my api endpoint's response to be cached in CloudFront, so I created the following simple middleware:
class CacheResponse
{
public function handle(Request $request, Closure $next, int $maxAge): mixed
{
$response = $next($request);
$response->header('Cache-Control', "public, max-age={$maxAge}");
$response->header('Pragma', "public");
return $response;
}
}
Then registered the middleware:
protected $middlewareAliases = [
...
'cache-response' => \App\Http\Middleware\CacheResponse::class,
];
Finally, I used the middleware like this:
Route::get('some/endpoint', [MyController::class, 'myMethod'])
->middleware('cache-response:300');
Once the changes were deployed, I hit the api endpoint of my app (several times) and CloudFront does not appear to be caching the api response as instructed. This is the response header I got back:
Access-Control-Allow-Origin: *
Cache-Control: max-age=300, public
Content-Length: 27
Content-Type: application/json
Date: Fri, 01 Sep 2023 02:05:07 GMT
Pragma: public
Via: 1.1 55cf94331c5a848a09407c283669c546.cloudfront.net (CloudFront)
X-Amz-Apigw-Id: KjgBCG7pIAMF5uw=
X-Amz-Cf-Id:552YO9QGBl47xgpFH4XkGotHMO97dVTYkyJYhYFLtx2ofl7_0iFRJA==
X-Amz-Cf-Pop: LHR62-C2
X-Amzn-Remapped-Date: Fri, 01 Sep 2023 02:05:07 GMT
X-Amzn-Requestid: 17b394fa-83bc-4fac-a91a-0214b841a7ed
X-Amzn-Trace-Id: Root=1-64f146d3-562460c90fcd8ed06eb52c84;Sampled=0;lineage=9fbc8014:0
X-Cache: Miss from cloudfront
Any ideas?
Your response headers won't control CloudFront behaviour.
You need to define a specific behaviour in your distribution associated with your API endpoint, then select the right cache policy.