How do I dynamically change cookie_lifetime? I'm trying to change cookie_lifetime dynamically in my D8 project, to set cookie_lifetime to 0 or to some value(for example 24 hours). I know that this can be partially acomplished by changing cookie_lifetime variable in sites/default/services.yml, but this is not my case.

I've tried to use this answer but looks like it works only when I use start() method of the session manager.

So how do I change dynamically cookie_lifetime for existing session?
Any answers appreciated, thanks in advance!
You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:

/mymodule/src/MySessionConfiguration.php:

&lt;?php

namespace Drupal\mymodule;

use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;

/**
 * Sets session cookie lifetime dynamically.
 */
class MySessionConfiguration extends SessionConfiguration {

  /**
   * {@inheritdoc}
   */
  public function getOptions(Request $request) {
    $options = parent::getOptions($request);

    // Set the cookie lifetime dynamically depending on the request.
    $options['cookie_lifetime'] = 30;

    return $options;
  }

}


Swap the service class in the container:

/mymodule/src/MymoduleServiceProvider.php:

&lt;?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container-&gt;getDefinition('session_configuration');
    $definition-&gt;setClass('Drupal\mymodule\MySessionConfiguration');
  }

}


See Altering existing services, providing dynamic services.