Fix Magento 2 issue “Area code not set”

0
7217
Fix Magento 2 issue
Fix Magento 2 issue "Area code not set"

“Area code not set” is a very common issue in Magento 2, especially, during a cron task or executing a console command. I will show you how to fix it in this post.

This error “Area code not set” often happens when you try to execute a console command or from a cron task. It happens because that command or cron task needs to query or update data from an object that requires current app state in order to get the correct values.

So, if you execute a provided Magento command, you might need to pass in the --area option, like this one below:

php bin/magento cache:flush --area=frontend

All area codes are defined in the Magento\Framework\App\Area class.

const AREA_GLOBAL = 'global';
const AREA_FRONTEND = 'frontend';
const AREA_ADMINHTML = 'adminhtml';
const AREA_DOC = 'doc';
const AREA_CRONTAB = 'crontab';
const AREA_WEBAPI_REST = 'webapi_rest';
const AREA_WEBAPI_SOAP = 'webapi_soap';
const AREA_GRAPHQL = 'graphql';

In other cases, e.g. custom commands, cron task… you will need to specify the area code before executing the code.

use Magento\Framework\App\State;

class CustomCommand extends Command
{
    /** @var \Magento\Framework\App\State **/
    private $appState;

    public function __construct(State $appState) {
        parent::__construct(self::COMMAND_NAME);
       
        $this->appState = $appState;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->appState->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
        // the rest of the code execution here
    }
}

There you go, you will not see the “Area code not set” error anymore in your Magento  2 application.

Have fun!