title: How to do a redirect from a Slim 4 middleware?
body: <p>I've been testing the new Slim 4 framework and redirects work fine for me in normal classes, but I cannot seem to get them working in middleware, where a response is dynamically generated (apparently?) by the Request Handler. When I try to redirect with a Location header, it simply fails to redirect, and my route continues to the original location.</p>
  
  <p>Here’s a basic version of my authentication middleware for testing:</p>
  
  <pre class="lang-php prettyprint-override"><code>use Psr\Http\Message\ServerRequestInterface as Request;
  use Psr\Http\Message\ResponseInterface as Response;
  use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
  
  class AuthMiddleware extends Middleware {
  
      public function __invoke(Request $request, RequestHandler $handler): Response {
          $response = $handler-&gt;handle($request);
          $loggedInTest = false;
          if ($loggedInTest) {
              echo "User authorized.";
              return $response;
          } else {
              echo "User NOT authorized.";
              return $response-&gt;withHeader('Location', '/users/login')-&gt;withStatus(302);
          }
      }
  }
  </code></pre>
  
  <p>Has anybody got this to work? And if so, how did you accomplish it? Thanks in advance.</p>