---
title: "Answering a script from a PSR-15 middleware"
manual: "TYPO3 Explained"
version: "main"
permalink: "https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-middleware@main"
source: "ExtensionArchitecture/Extbase/BeyondHtml/Middleware.rst"
rendered: "2026-11-18T15:43:17+00:00"
---

# Answering a script from a PSR-15 middleware {#extbase-beyond-html-middleware}

A [middleware](https://docs.typo3.org/permalink/t3coreapi:request-handling@main)
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](https://docs.typo3.org/permalink/t3coreapi:extbase-no-frontend-middleware@main).

**On this page**

-   [When a middleware endpoint fits better than a page type](https://docs.typo3.org/permalink/t3coreapi:when-a-middleware-endpoint-fits-better-than-a-page-type@main)
-   [A middleware that answers with JSON from Extbase data](https://docs.typo3.org/permalink/t3coreapi:a-middleware-that-answers-with-json-from-extbase-data@main)
-   [Matching the endpoint URL within the site and language](https://docs.typo3.org/permalink/t3coreapi:matching-the-endpoint-url-within-the-site-and-language@main)
-   [Placing the endpoint middleware in the frontend chain](https://docs.typo3.org/permalink/t3coreapi:placing-the-endpoint-middleware-in-the-frontend-chain@main)
-   [Next steps after answering from a middleware](https://docs.typo3.org/permalink/t3coreapi:next-steps-after-answering-from-a-middleware@main)

## When a middleware endpoint fits better than a page type {#extbase-beyond-html-middleware-when}

The [seats example](https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-ajax-example@main) loads the free
seats of each conference once per page view, from a
[typeNum page type](https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-page-type@main). 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](https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-jsonview@main), 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 {#extbase-beyond-html-middleware-endpoint}

The middleware below answers requests to `api/seats.json` with the
same JSON array as the seats action of the page type. Any other request is
passed on to the next middleware:

**EXT:my_extension/Classes/Middleware/ConferenceSeatsMiddleware.php**

```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\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](https://docs.typo3.org/permalink/t3coreapi:extbase-no-frontend-middleware-attributes@main).
    `findUpcomingInFolders()` stands for such a method, and
    `getSeatsLeft()` for the model method of the seats example.
-   `\TYPO3\CMS\Core\Http\JsonResponse` encodes the array and sets the
    content type `application/json`.
-   The response can carry any status code. A request with another method than
    `GET` receives `405 Method Not Allowed` with an `Allow` header.
-   `Cache-Control: no-store` 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 a `max-age` instead, and the endpoint can keep expensive
    results in a cache of the
    [caching framework](https://docs.typo3.org/permalink/t3coreapi:caching@main).

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](https://docs.typo3.org/permalink/t3coreapi:extbase-no-frontend-middleware-access@main).

## Matching the endpoint URL within the site and language {#extbase-beyond-html-middleware-url}

The site middleware stores the result of its URL matching in the
[routing request attribute](https://docs.typo3.org/permalink/t3coreapi:typo3-request-attribute-routing@main). Its method
`getTail()` returns the part of the path that follows the base of the
site language. For `https://example.org/de/api/seats.json`, with the
language base `https://example.org/de/`, the tail is
`api/seats.json`.

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:

**EXT:my_extension/Classes/Controller/ConferenceController.php (excerpt)**

```php
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-seats-url="{seatsUrl}"`, and the
[script of the seats example](https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-ajax-script@main) works
unchanged. To ask again every 30 seconds, it calls its function on an
interval:

**EXT:my_extension/Resources/Public/JavaScript/conference-seats.js (excerpt)**

```javascript
const list = document.querySelector('[data-seats-url]');
if (list) {
  showSeatsLeft(list);
  setInterval(() => showSeatsLeft(list), 30000);
}
```

## Placing the endpoint middleware in the frontend chain {#extbase-beyond-html-middleware-ordering}

Where the middleware sits in the chain decides what it has available and
which of the frontend's checks apply to it:

**EXT:my_extension/Configuration/RequestMiddlewares.php**

```php
<?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/cms-frontend/authentication`, 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.
-   Before `typo3/cms-frontend/page-resolver`, the URL does not have to belong
    to a page. TYPO3 would otherwise answer `api/seats.json` with
    "page not found" before the middleware sees the request.

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](https://docs.typo3.org/permalink/t3coreapi:extbase-no-frontend-middleware-ordering@main).

## Next steps after answering from a middleware {#extbase-beyond-html-middleware-next}

The endpoint in this example runs Extbase without any of its configuration.
[Extbase in middlewares](https://docs.typo3.org/permalink/t3coreapi:extbase-no-frontend-middleware@main) describes what
the repositories do in that situation and what the middleware has to supply.
[Ways to deliver non-HTML output from TYPO3](https://docs.typo3.org/permalink/t3coreapi:extbase-beyond-html-options@main) compares the middleware with the other options.
