let's say we have executes below magento-2 code at one single request,

namespace namespace\CookieDemo\Model;

 * Class Cookie
class Cookie
     * @var \Magento\Framework\Stdlib\CookieManagerInterface CookieManagerInterface
    private $cookieManager;

     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory CookieMetadataFactory
    private $cookieMetadataFactory;

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

    /** Set Custom Cookie using Magento 2 */
    public function setCustomCookie()
        $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();

        return $this->cookieManager->setPublicCookie(

    /** Get Custom Cookie using */
    public function getCustomCookie()
        return $this->cookieManager->getCookie(

Let's say we are calling it anyhow for temp.

$object->setCustomCookie(); // cookie has been set
echo $object->getCustomCookie(); // This will print nothing at first request. what if I want to get value of cookie here?

But whenever we will make another request we will get the value because cookie has been set already.

Please provide solution to save my day. Thanks in advance.


Your Answer

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

Browse other questions tagged or ask your own question.