title: PHP - Guzzle Middleware
body: <p>I'm using the Pole Emploi's API,but I encounter 401 error 25 minutes later, when my token expires.</p>
  
  <p>I looked for a way to get a new token and retry the request, but no way for me to understand how Middlewares work, and if I should use a middleware for my needings.</p>
  
  <p>On Guzzle's docs this is written : </p>
  
  <blockquote>
    <p>Middleware functions return a function that accepts the next handler to invoke. This returned function then returns another function that acts as a composed handler-- it accepts a request and options, and returns a promise that is fulfilled with a response. Your composed middleware can modify the request, add custom request options, and modify the promise returned by the downstream handler.</p>
  </blockquote>
  
  <p>And this is an example code from the docs : </p>
  
  <pre><code>use Psr\Http\Message\RequestInterface;
  
  function my_middleware()
  {
      return function (callable $handler) {
          return function (RequestInterface $request, array $options) use ($handler) {
              return $handler($request, $options);
          };
      };
  }
  </code></pre>
  
  <p>So I think I need to manage the "promise" to see if its HTTP code is 401, and then get a new token and retry the request ?</p>
  
  <p>I'm lost, so I would appreciate if someone can explain me the logic of this with different words maybe :)</p>
  
  <p>Thank you in advance.</p>