Extbase in middlewares 

Middlewares inspect and modify the request and response: adding headers, short-circuiting with a redirect, answering a route directly. Extensions sometimes want domain data at that point, like an API endpoint or a conditional redirect based on a record.

A middleware runs inside a request, but Extbase does not see that request. Extbase reads its configuration from the request its own bootstrap hands it when a plugin or a module runs, or from the global request, which TYPO3 sets only after the whole middleware chain has run. In a middleware, Extbase is therefore in the same situation as in a command, wherever the middleware sits in the chain. What differs is how much the request already knows, and with that, what the middleware can tell Extbase itself.

How middlewares are written, registered and ordered is described in Middlewares (request handling).

What a middleware has at each point of the frontend chain 

The frontend middleware chain adds to the request step by step. For the use of Extbase, three points matter:

Before the site is resolved
The request has no site and no language attribute. The middleware cannot tell which site the request belongs to.
After the site is resolved
The site and language request attributes are set by the middleware typo3/cms-frontend/site. The site's settings, its languages and its configuration are available. After typo3/cms-frontend/authentication, the frontend user is known as well.
After the frontend is prepared
The page, its TypoScript and the language of the page are established. The middleware that does this is internal, and the full TypoScript is only calculated when the page is not delivered from the cache.

At none of these points can Extbase read its own configuration. Repositories work, with the same defaults as in a command: storagePid 0, no recursive setting, and the default language until the frontend has been prepared. See What Extbase persistence does without a request.

Passing the middleware's request to Extbase by hand does not help. With a request, Extbase reads its configuration from the TypoScript the request carries, and every repository query throws an exception when that TypoScript is missing or incomplete:

  • Before the frontend is prepared, the request carries no TypoScript at all.
  • After the frontend is prepared, the request carries the full TypoScript only when the page was not delivered from the cache. On a cached page, the queries throw as well.

Without a request, Extbase reads no TypoScript, and its queries run with the defaults described above.

Supplying storage pages and language from the request attributes 

After the site is resolved, the request carries what Extbase is missing, and a middleware can pass it to the query itself. A middleware that answers a JSON endpoint with conferences could look like this:

EXT:my_extension/Classes/Middleware/ConferenceApiMiddleware.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Middleware;

use MyVendor\MyExtension\Domain\Repository\ConferenceRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;

class ConferenceApiMiddleware implements MiddlewareInterface
{
  public function __construct(
    protected readonly ConferenceRepository $conferenceRepository,
  ) {}

  public function process(
    ServerRequestInterface $request,
    RequestHandlerInterface $handler,
  ): ResponseInterface {
    if (!str_ends_with($request->getUri()->getPath(), '/api/conferences.json')) {
      return $handler->handle($request);
    }

    $site = $request->getAttribute('site');
    $siteLanguage = $request->getAttribute('language');
    // Not set for URLs outside any site
    if (!$site instanceof Site || !$siteLanguage instanceof SiteLanguage) {
      return $handler->handle($request);
    }

    $storagePid = (int)$site->getSettings()->get('myExtension.conferenceStoragePid', 0);
    if ($storagePid === 0) {
      return $handler->handle($request);
    }

    $conferences = $this->conferenceRepository->findPublishedForApi(
      [$storagePid],
      LanguageAspectFactory::createFromSiteLanguage($siteLanguage),
    );

    $data = [];
    foreach ($conferences as $conference) {
      $data[] = [
        'title' => $conference->getTitle(),
        'date' => $conference->getEventDate()?->format('Y-m-d'),
      ];
    }
    return new JsonResponse($data);
  }
}
Copied!

The middleware tests for the attributes rather than assuming them. A URL that belongs to no site has neither, and the middleware hands the request on.

The storage folder comes from a site setting. Each site can then name its own folder, and the middleware needs no TypoScript. The extension can define the setting in its site set:

EXT:my_extension/Configuration/Sets/MyExtension/settings.definitions.yaml
settings:
  myExtension.conferenceStoragePid:
    label: 'Conference storage folder'
    description: 'Folder that stores the conferences of this site.'
    type: page
    default: 0
Copied!

The language aspect is built from the language attribute, the same way the frontend builds it for the page, see Setting the language explicitly. A repository method can take both as arguments:

EXT:my_extension/Classes/Domain/Repository/ConferenceRepository.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Repository;

use MyVendor\MyExtension\Domain\Model\Conference;
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;
use TYPO3\CMS\Extbase\Persistence\Repository;

class ConferenceRepository extends Repository
{
  /**
   * @param int[] $storagePageIds
   * @return QueryResultInterface<Conference>
   */
  public function findPublishedForApi(
    array $storagePageIds,
    LanguageAspect $languageAspect,
  ): QueryResultInterface {
    $query = $this->createQuery();
    $query->getQuerySettings()
      ->setStoragePageIds($storagePageIds)
      ->setLanguageAspect($languageAspect);
    $query->matching($query->equals('published', true));
    $query->setOrderings(['conferenceDate' => QueryInterface::ORDER_ASCENDING]);

    return $query->execute();
  }
}
Copied!

It is recommended to pass the language aspect to the query settings like this rather than to change the language aspect of the global context. The context is shared by everything that runs later in the request.

Records restricted to frontend user groups in a middleware 

Extbase decides which visibility rules apply by looking at the global request. In a middleware there might not be one yet, so Extbase applies the rules it uses outside the frontend: hidden records and records outside their start and end time are left out, but restrictions to frontend user groups are not checked.

Ordering a middleware that uses Extbase 

A middleware that needs the site has to run after typo3/cms-frontend/site, and it has to say so in its registration. A middleware ordered without constraints may run anywhere in the chain. An API endpoint can also run before typo3/cms-frontend/page-resolver, so that its route does not have to match a page:

EXT:my_extension/Configuration/RequestMiddlewares.php
<?php

declare(strict_types=1);

use MyVendor\MyExtension\Middleware\ConferenceApiMiddleware;

return [
  'frontend' => [
    'myvendor/my-extension/conference-api' => [
      'target' => ConferenceApiMiddleware::class,
      'after' => [
        'typo3/cms-frontend/site',
      ],
      'before' => [
        'typo3/cms-frontend/page-resolver',
      ],
    ],
  ],
];
Copied!

The calculated order is shown in the System > Configuration module, see Configuring middlewares.

When the work belongs somewhere else than a middleware 

Having to supply storage pages, language and access rules by hand is a sign the work may fit better elsewhere:

  • An Extbase plugin. A plugin gets its configuration, its storage pages and the frontend's visibility rules from Extbase. Placed on a page of its own, with a page type and a route enhancer, it can answer JSON as well, see Delivering Extbase output with a typeNum page type.
  • A service called from a controller, when the middleware only exists to prepare data for a plugin.
  • The database API, when the middleware only needs a few fields. With the frontend restriction container it applies the same visibility rules as the frontend, needs no configuration, and costs less than Extbase in a request that is otherwise served from the cache, see Using Extbase in the middleware documentation.

Next steps for Extbase in middlewares 

A command meets the same defaults with no request at all. How to work with them there is described in Extbase on the command line.

How a middleware delivers its data to a script, from matching the URL to the response, is described in Answering a script from a PSR-15 middleware.

The overview of all contexts without a frontend is in Using Extbase outside a frontend request.