title: http-proxy-middleware change headers asynchronously
body: <p>I'm using <a href="https://github.com/chimurai/http-proxy-middleware" rel="nofollow noreferrer">http-proxy-middleware</a> in NodeJS to proxy a PHP site that does authentication.</p>
  <p>The PHP site returns a header &quot;saml-user-id&quot;.<br />
  I use this saml-user-id to generate a token which I want to add as cookie. I need to lookup the user in the database, so it needs to work asynchronously.</p>
  <p>The code looks like this:</p>
  <pre class="lang-js prettyprint-override"><code>// DOESN'T WORK
  exports.proxySimpleSamlMiddleware = createProxyMiddleware(['/saml'], {
      ssl: {
          key: fs.readFileSync('/path/to/my.key'),
          cert: fs.readFileSync('path/to/my.crt'),
      },
      target: 'https://127.0.0.1:8443',
      secure: false,
      logLevel: 'debug',
      changeOrigin: true,
      onProxyRes: async (proxyRes, req, res) =&gt; { // &lt;-- ASYNCHRONOUS
  
          let tokenCookie = 'token=';
  
          if (proxyRes.headers['saml-user-id']) {
              const userId = proxyRes.headers['saml-user-id'];
              const token = await getNewToken(userId);
              tokenCookie = `token=${token}; path=/; httponly; samesite=lax`;
          }
  
          // Set the 'token' cookie
          // (simplified, in reality I read the existing cookies from the headers
          // and add this cookie to the list)
          proxyRes.headers['set-cookie'] = tokenCookie;
      },
  });
  </code></pre>
  <p>The above code doen't work. No headers are changed, and I get an error (&quot;Cannot set headers after they are sent to the client&quot;). I guess that this is because of the asynchronous function in onProxyRes.</p>
  <p>If I change the code to this:</p>
  <pre class="lang-js prettyprint-override"><code>    // DOESN'T WORK ASYNCHRONOUSLY
      onProxyRes: (proxyRes, req, res) =&gt; { // &lt;-- REMOVED ASYNC
          let tokenCookie = 'token=my-new-token';
          proxyRes.headers['set-cookie'] = tokenCookie;
      },
  </code></pre>
  <p>Then the &quot;token&quot; cookie is set to &quot;my-new-token&quot; as expected. This is not an option because the change I want to make is asynchronous.</p>
  <p>I have experimented with &quot;responseIntercepter&quot;:</p>
  <pre class="lang-js prettyprint-override"><code>    // DOESN'T WORK
      selfHandleResponse: true,
      onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) =&gt; {
          let tokenCookie = 'token=my-new-token';
          proxyRes.headers['set-cookie'] = tokenCookie;
          return responseBuffer;
      }),
  </code></pre>
  <p>But this doesn't update the &quot;token&quot; cookie either.</p>
  <p>My question:<br />
  Is there a way using http-proxy-middleware to change the headers asynchronously?</p>