Answering a script from a PSR-15 middleware
A middleware can answer a request before TYPO3 resolves a page. No page is rendered, no TypoScript is evaluated, and the response is entirely under the extension's control. For small data that a script requests often, this is the lightest way TYPO3 offers.
This page shows what such an endpoint needs to deliver its data: a URL within the site, a place in the middleware chain, and a response. How Extbase repositories behave in a middleware, and what they need to be told, is described in Extbase in middlewares.
On this page
When a middleware endpoint fits better than a page type
The seats example loads the free seats of each conference once per page view, from a typeNum page type. If the list should stay current while a visitor looks at it, the script asks again every 30 seconds. Every one of these requests runs the frontend of a page type: TYPO3 resolves the page, checks access and loads the TypoScript, only to run one small query.
A middleware answers the same request with the query alone. In exchange, it does without what the page brings:
- No page cache. The middleware runs on every request, and caching is up to the extension.
- No plugin. There is no Extbase controller, no JsonView, no FlexForm and no TypoScript configuration. Extbase repositories use their defaults unless the middleware supplies storage pages and language itself.
- No page access checks. The endpoint decides who may read its data.
A middleware fits when the data needs none of these: values that change often, are requested often, and are the same for everybody or depend only on the site, the language or the frontend user. When the data depends on what an editor configured in a content element, a page type is the better tool.
A middleware that answers with JSON from Extbase data
The middleware below answers requests to api/ with the
same JSON array as the seats action of the page type. Any other request is
passed on to the next middleware:
<?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\Http\JsonResponse;
use TYPO3\CMS\Core\Routing\SiteRouteResult;
use TYPO3\CMS\Core\Site\Entity\Site;
class ConferenceSeatsMiddleware implements MiddlewareInterface
{
public function __construct(
protected readonly ConferenceRepository $conferenceRepository,
) {}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler,
): ResponseInterface {
$routing = $request->getAttribute('routing');
$site = $request->getAttribute('site');
if (!$routing instanceof SiteRouteResult
|| !$site instanceof Site
|| trim($routing->getTail(), '/') !== 'api/seats.json'
) {
return $handler->handle($request);
}
if ($request->getMethod() !== 'GET') {
return new JsonResponse(null, 405, ['Allow' => 'GET']);
}
$storagePid = (int)$site->getSettings()->get('myExtension.conferenceStoragePid', 0);
if ($storagePid === 0) {
return $handler->handle($request);
}
$seats = [];
foreach ($this->conferenceRepository->findUpcomingInFolders([$storagePid]) as $conference) {
$seats[] = [
'uid' => $conference->getUid(),
'seatsLeft' => $conference->getSeatsLeft(),
];
}
return new JsonResponse($seats, 200, ['Cache-Control' => 'no-store']);
}
}
- The storage folder comes from a site setting, and the repository method
passes it to the query, as described in
Supplying storage pages and language from the request attributes.
findstands for such a method, andUpcoming In Folders () getfor the model method of the seats example.Seats Left () \TYPO3\encodes the array and sets the content typeCMS\ Core\ Http\ Json Response application/.json - The response can carry any status code. A request with another method than
GETreceives405 Method Not Allowedwith anAllowheader. Cache-tells browsers and proxies not to keep the numbers, because they are meant to be current. Data that may be a little older can send aControl: no- store max-instead, and the endpoint can keep expensive results in a cache of the caching framework.age
The numbers in this example are public. When a table restricts records to frontend user groups, the middleware has to check the restrictions itself, see Records restricted to frontend user groups in a middleware.
Matching the endpoint URL within the site and language
The site middleware stores the result of its URL matching in the
routing request attribute. Its method
get returns the part of the path that follows the base of the
site language. For https://, with the
language base https://, the tail is
api/.
Comparing the tail instead of the whole path makes the endpoint available in
every site and every language under the same relative URL, and the request
attributes
site
and
language
tell the middleware which one was
requested. A language base without a trailing slash leaves a slash at the start
of the tail, which
trim removes.
The list template receives the URL of the endpoint from its action, built from the base of the current language:
public function listAction(): ResponseInterface
{
$language = $this->request->getAttribute('language');
$this->view->assignMultiple([
'conferences' => $this->conferenceRepository->findUpcoming(),
'seatsUrl' => rtrim((string)$language->getBase(), '/') . '/api/seats.json',
]);
return $this->htmlResponse();
}
The template writes it into the same data- attribute as before,
data-, and the
script of the seats example works
unchanged. To ask again every 30 seconds, it calls its function on an
interval:
const list = document.querySelector('[data-seats-url]');
if (list) {
showSeatsLeft(list);
setInterval(() => showSeatsLeft(list), 30000);
}
Placing the endpoint middleware in the frontend chain
Where the middleware sits in the chain decides what it has available and which of the frontend's checks apply to it:
<?php
declare(strict_types=1);
use MyVendor\MyExtension\Middleware\ConferenceSeatsMiddleware;
return [
'frontend' => [
'myvendor/my-extension/conference-seats' => [
'target' => ConferenceSeatsMiddleware::class,
'after' => [
'typo3/cms-frontend/authentication',
],
'before' => [
'typo3/cms-frontend/page-resolver',
],
],
],
];
- After
typo3/, the site and the language are resolved and the frontend user is known. The frontend authentication runs after the maintenance mode, so the endpoint does not answer while the site is in maintenance mode.cms- frontend/ authentication - Before
typo3/, the URL does not have to belong to a page. TYPO3 would otherwise answercms- frontend/ page- resolver api/with "page not found" before the middleware sees the request.seats. json
Middlewares that run later in the chain do not run at all for a request the endpoint answers. Middlewares that run earlier still process its response on the way back.
The ordering of middlewares in general, and how to check the calculated order, is described in Ordering a middleware that uses Extbase.
Next steps after answering from a middleware
The endpoint in this example runs Extbase without any of its configuration. Extbase in middlewares describes what the repositories do in that situation and what the middleware has to supply. Ways to deliver non-HTML output from TYPO3 compares the middleware with the other options.