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\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
- Inject
Magento\Framework\App\State. - Call
setAreaCodeonce early, before any area-bound service. - Use the area your work runs in (adminhtml for admin tasks).
$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.
$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
emulateAreaCodefor one-off area-bound work. - Extend
Console\Commandso the framework manages the area.