 <p>Thanks for the heads up about the bug report and fix. I feel the need to give an answer to this question though, just in case you haven't ditched PHP and Slim framework altogether. Hopefully, it will be of help to someone else.</p> <p>My approach to this would be:</p> <pre><code>&lt;?php use Slim\Http\Request; use Slim\Http\Response; class AuthenticationMiddleware { public function isAuthenticated($userid, $authorization) { //do data validation here return false; } public function createErrorResponse($code, $msg, Response $response) { return $response-&gt;withStatus($code) -&gt;withHeader('Content-Type', 'application/json;charset=utf-8') -&gt;withJson($msg); } public function __invoke(Request $request, Response $response, $next) { $userid = $request-&gt;getHeaderLine('userid'); $authorization = $request-&gt;getHeaderLine('Authorization'); if(!$this-&gt;isAuthenticated($userid, $authorization)) { $msg = 'You are unauthenticated. Please login again'; $code = 400; $this-&gt;createErrorResponse($code, $msg, $response); } else { $response = $next($request, $response); } return $response; } } </code></pre> <p>Let me just say this. I would abstract a few stuff here in this code so I don't end up repeating myself. I see you repeating:</p> <pre><code>public function createErrorResponse($code, $msg, Response $response) { return $response-&gt;withStatus($code) -&gt;withHeader('Content-Type', 'application/json;charset=utf-8') -&gt;withJson($msg); } </code></pre> <p>In all your middleware and perhaps, in your routes. Hope this sets someone on the right track.</p>