How do I set a cookie using $response->headers->setCookie() in a form submission handler? I read on Deprecate user_cookie_save() and user_cookie_delete(). that user_cookie_save() will be deprecated in Drupal 9 and that we should now use the Symfony's method, as in the following code.

$response = new Response();
$response-&gt;headers-&gt;setCookie(new Cookie('foo', 'bar'));
return $response-&gt;send();


If I use that code in a submission handler of a custom form, $response-send() just returns an empty page, rather than my site. What am I missing here? 

EDIT:

OK, so I moved my cookie setting code to a controller method:

public function setusercookies($zip, $license){
    $destination = urldecode(\Drupal::request()-&gt;query-&gt;get('destination'));
    $response = new RedirectResponse(!empty($destination) ? $destination : '/');
    $response-&gt;headers-&gt;setCookie(new Cookie('zip', $zip, strtotime( '+1 year' ), '/'));
    $response-&gt;headers-&gt;setCookie(new Cookie('license', $license, strtotime( '+1 year' ), '/'));
    $response-&gt;send();
    return $response;
}


And in my form's submitForm function:

$form_state-&gt;setRedirect('mycontroller.setusercookies', [
      'zip' =&gt; $zip,
      'license' =&gt; $license
    ], [
      'destination' =&gt; $destination
    ]);


In both Chrome and Firefox inspectors, I can see that the cookies are set, but now I can't get them back out. I've tried both:

$zip = \Drupal::request()-&gt;cookies-&gt;get('zip', 'oops');
/* and */
$zip = $_COOKIE['zip'];


UPDATE 2:
Starting to think it's an environment issue ... lando with pantheon recipe.

SOLVED:
The entire time it seems it was a platform issue:

https://pantheon.io/docs/caching-advanced-topics/#using-your-own-session-style-cookies
You can't send a response from custom code in Drupal. You have to return it from a controller.

You can also set a response or add the cookie to an existing response in an event subscriber. In your case set the response in form submit, then Drupal does this for you in a core event subscriber:

$form_state-&gt;setResponse($response);


To avoid the empty page you probably want to fill the response with content or add the cookie to a redirect response to display a different page.



Don't $response-&gt;send()

To explain why not to send a response. When you find a code example for the Symfony component HttpFoundation sending a response, it isn't valid for custom code in Drupal. See the warning in this doc:


  This article explains how to use the HttpFoundation features as an
  independent component in any PHP application. In Symfony applications
  everything is already configured and ready to use. Read the Controller
  article to learn about how to use these features when creating
  controllers.


In addition the Drupal kernel is wrapped in stack middlewares using Stack/Builder. So sending a response can even be a security risk if you have for example installed a middleware providing security checks.