How to get store code by store cookie Magento 2?

You can get the store code value from the cookie name store in Magento 2.

This article will be useful while you have multiple stores set up in your store.

While you switch any store from the site, Magento adds a logic to add a new cookie called store with a value containing the current selected store.

By default, you can’t able to find a cookie key store in your browser but when you switch the stores, You can see one new cookie is available to the site with the cookie key  store and value as the store_code. (Example, store = default)

<?php
declare(strict_types=1);

namespace Rbj\CookieDemo\Model;

use Magento\Store\Api\StoreCookieManagerInterface;

class Cookie
{
    public function __construct(
        private readonly StoreCookieManagerInterface $storeCookieManager
    ) {
    }

    /** Get Cookie value from cookie store. */
    public function setCustomCookie(): string
    {
        return $this->storeCookieManager->getStoreCodeFromCookie();
    }
}

Using the above way, You can directly use the Magneto interface, Magento\Store\Api\StoreCookieManagerInterface to fetch the store code from the cookie value.

A method getStoreCodeFromCookie() fetch the cookie value from the store cookie key.