Servers cannot set cookies on requests

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-11-21

I had the following (buggy) code to store locale in a cookie in some middleware. I tried added it to the incoming request object like so:

<?php

  $request->cookie("locale", $locale, $minutesToStore);
  $response = $next($request);

This was wrong. Why? You can only set cookies on responses, not requests.

Here's the fix - something working with the $response object.

<?php

  $response = $next($request);
  $response->cookie("locale", $locale, $minutesToStore);