You can try out an event response event subscriber. For E.g:
Create a file in CUSTOM_MODULE/src/EventSubscriber/SetSessionCookieSubscriber.php
namespace Drupal\CUSTOM_MODULE\EventSubscriber;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class SetSessionCookieSubscriber implements EventSubscriberInterface {
public function onResponse(FilterResponseEvent $event) {
/** @var Request $request */
$request = $event->getRequest();
// Check if this is the right request, for example posting facets
$session = $request->getSession();
// Check for session values
$response = $event->getResponse();
/** Your custom code goes here */
$response->headers->setCookie(new Cookie(...));
}
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['onResponse'];
return $events;
}
}
Register it in your services file CUSTOM_MODULE.services.yml
services:
CUSTOM_MODULE.setsessioncookie:
class: Drupal\CUSTOM_MODULE\EventSubscriber\SetSessionCookieSubscriber
tags:
- { name: event_subscriber }