How to get current area code in Magento 2

In this tutorial, I will explain to you how to check the current area code in Magento 2. Sometimes, it may be required to develop functionality based on the area like only for the frontend side or only for the backend side.

When we need to execute a script from the root folder at that time, how can we detect the current area of Magento 2? We can check the current area of Magento 2 using two methods.

  • By ObjectManager Method
  • By Construct Method

By ObjectManager Method:

Note: As per my opinion, please don’t use this method. Use always construct method.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stateArea = $objectManager->get('Magento\Framework\App\State');
echo $stateArea->getAreaCode(); // (return values from one of frontend, backend or webrest_api)

By Construct Method:


namespace Mageclues\Areacode\Block;

use Magento\Framework\App\State;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class Areastate extends Template
     * @var StateArea
    protected $_stateArea;

     * @param Context $context
     * @param State   $stateArea
     * @param array   $data
    public function __construct (
        Context $context,
        State $stateArea,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_stateArea = $stateArea;

    public function getCurrentAreaCode()
          return $this->_stateArea->getAreaCode();

After that, you can use this block class in your layout file or construct class and get area code by getCurrentAreaCode() function.

I hope this blog is helpful for you. Please leave comment if you have any question.

thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *