I've followed this question but set method mentioned there is outdated (Reference: Magento\Framework\App\PageCache\FormKey::set()).

So, a cookie is created like this:

public function set($value, PublicCookieMetadata $metadata)

Where $metadata should be an instance of PublicCookieMetadata.

In one of the plugin I'm using $this->customerCountry->set('India', 10); I know I'm doing wrong here. Instead of passing 10 as the second parameter I need to pass instance of PublicCookieMetadata. How I can do that? I've tried $this->customerCountry->set('India', PublicCookieMetadata $metadat =null); which seems to be wrong. How I can creat and set duration of the cookie?

1 Answer 1


you need to declare in your class constructor an instance of \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory like this:

protected $cookieMetadataFactory;
public function __construct(
    \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
) {
    $this->cookieMetadataFactory = $cookieMetadataFactory;

Then you can get generate the PublicCookieMetadata like this

$cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata()
            ->setDuration(lifetime goes here)
            ->setPath(cookie path goes here)
            ->setDomain(domain goes here)
            ->setSecure(is secure goes here)
            ->setHttpOnly(http only flag goes here);

then use the variable $cookieMetadata as your parameter.

You can find examples of you to generate the cookie metadata in

  • \Magento\Backend\Model\Auth\Session::prolong()
  • \Magento\Persistent\Model\Session::setCookie()
  • \Magento\Sales\Helper\Guest::setGuestViewCookie()
  • \Magento\Store\Model\StoreCookieManager::setStoreCookie()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.