Skip to content
Latchkey

Magento "Area code not set" (LocalizedException) in CI

Many Magento services need to know which area (frontend, adminhtml, crontab) they run in. A standalone script or command that touches those services without first setting the area code triggers a LocalizedException.

What this error means

A custom CLI command or data script fails with "Area code not set: Area code must be set before starting a session" or, on a second call, "Area code is already set".

Magento
Magento\Framework\Exception\LocalizedException: Area code not set:
Area code must be set before starting a session.
#0 .../Magento/Framework/App/State.php(...): Magento\Framework\App\State->getAreaCode()

Common causes

A script uses services before setting the area

Block rendering, email, and many models require an area; calling them from a bare script leaves the area code unset.

The area code is set twice

Calling setAreaCode after Magento already set it (or twice in one process) throws "Area code is already set".

How to fix it

Set the area code before using services

  1. Inject Magento\Framework\App\State.
  2. Call setAreaCode once early, before any area-bound service.
  3. Use the area your work runs in (adminhtml for admin tasks).
PHP
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);

Emulate an area for a scoped block

When the area is already set, emulate it just for the call instead of setting it again.

PHP
$emulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND);

How to prevent it

  • Set the area code once at the start of standalone scripts.
  • Use emulateAreaCode for one-off area-bound work.
  • Extend Console\Command so the framework manages the area.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →