Limit Ajax Routing

I am trying to limit AJAX requests to routes that begin with the ‘/ajax/’ prefix. Similarly, I do not want the other routes in my website to be accessible using AJAX requests.

Rather than adding checks in all my routes, it seems to me that a Middleware would be a better site-wide way to imposing this rule.

I have written this:

class AjaxMiddleware implements MiddlewareInterface

    public function process(Request $request, Handler $handler): ResponseInterface
        $path = $request->getUri()->getPath();
        // validate Ajax requests
        if ($isAjax) {
            if (stripos($path, '/ajax/') !== 0) {
                throw new HttpForbiddenException($request, "Ajax Not Allowed");
        // validate non-Ajax requests 
        else {
            if (stripos($path, '/ajax/') === 0) {
                throw new HttpBadRequestException($request, "Ajax Routes Not Allowed");

        return $handler->handle($request);

    private function isAjax(Request $request): bool
        return strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest';

My question is whether this Middleware should be added before or after adding the RoutingMiddleware in the bootstrap file?

Slim 4 currently uses a Last In, First Out (LIFO) model for middleware.

To handle 404 errors correctly, I would recommend adding the AjaxMiddleware before the RoutingMiddleware.

$app->add(AjaxMiddleware::class); // <--- here