How add new status to response through Middleware? [Solved]

Hi. I try return new response code through my middleware class (check if user has access to page):

$app->get('/testd/', function (Request $request, Response $response) use ($session) {
    $page = preparePage();

    return $response;
})->add(new CheckAllowMiddleware(['dev']));

middleware work fine, but return 200 status (not 403)

BUT if I add middleware to all app routes then status codes returns is normal but for all pages

$app->add(new CheckAllowMiddleware(['dev'])

What am I doing wrong?


My CheckAllowMiddleware in simple:

class CheckAllowMiddleware
    public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
        $serverParams = $request->getServerParams();
        $realIP = $serverParams['REMOTE_ADDR'];

        if (!in_array($realIP, $this->checkAllowedIPs())) {
            $response = new Response();
            $newResponse = $response->withStatus(403);
            $newResponse->getBody()->write('Access Denied');

            return $newResponse;

        return $handler->handle($request);

Solution founded on this forum - Before middleware order