title: Propagate WebClient Response Header to Client in WebFlux application
body: <p>I am writing a thin proxy for an API using Swagger codegen for both Server and Client. Now the backend server sometimes wants to include specific headers (ETag, Location, …) in its responses. These should be passed through to the original caller. I have tried to configure my WebClient to use the Reactor Context for this task</p>
  <h2>WebClient</h2>
  <pre class="lang-java prettyprint-override"><code>WebClient.builder()
              .filter((req, exc) -&gt; Mono.defer(() -&gt; exc.exchange(req)
                  .flatMap(response -&gt; Mono.just(response).contextWrite(
                      context -&gt; {
                          return response.headers().header(&quot;ETag&quot;).stream().findFirst().map(h -&gt; {
                              return context.put(&quot;ETag&quot;, h);
                          }).orElse(context);
                      }))))
  </code></pre>
  <p>This actually gets called and creates a new context object. But when I try to access it either in the Controller or a WebFilter, the original, unmodified Context ist seen.</p>
  <h2>Controller</h2>
  <pre class="lang-java prettyprint-override"><code>        return api.getFoo(id).flatMap(foo -&gt; Mono.deferContextual(ctx -&gt; {
              return Mono.just(ResponseEntity.ok().header(&quot;ETag&quot;, ctx.getOrDefault(&quot;ETag&quot;, &quot;&quot;)).body(foo));
          }));
  </code></pre>
  <h2>WebFilter</h2>
  <pre class="lang-java prettyprint-override"><code>        serverWebExchange.getResponse().beforeCommit(() -&gt; Mono.deferContextual(Mono::just).doOnNext(ctx -&gt; {
              serverWebExchange.getResponse().getHeaders().add(&quot;ETag&quot;, ctx.getOrDefault(&quot;ETag&quot;, &quot;&quot;));
          }).then());
  </code></pre>
  <p>I cannot easily access the original response object, since Swagger calls <code>bodyToMono</code> on it in its generated <code>invokeApi</code> method.</p>
  <p>Honestly, I am at a loss on how Reactor's Context works. To me it seems I am trying to assing the Context of the wrong Mono? But then, how can I write to the „global“ Context for my Controller from within it? Or is there some other way to achieve this kind of header propagation?</p>