How to Intercept a Request and Add Headers in WebFlux?
Last Updated :
28 May, 2024
Spring WebFlux is the reactive stack web framework that allows developers to build non-blocking, asynchronous applications that can handle a large number of concurrent with fewer hardware resources. In this article, we will explore how to intercept the HTTP requests in the Spring WebFlux application and modify them by adding custom headers. This capability can be useful for a variety of cross-cutting concerns such as authentication, logging, and modifying the request or response headers.
Intercepting Requests in WebFlux
In Spring WebFlux, we can intercept the requests using a WebFliter. The WebFliter can operate on the non-blocking reactive WebFlux stack and allows us to manipulate the request and response to the objects before they can reach the controllers or after they can sent back to the client.
Key Terminologies:
- Spring WebFlux: The reactive web framework is part of the Spring 5 framework and it can designed to build reactive applications. It supports non-blocking, event-driven programming and works on the Reactive Streams specification.
- Reactive Programming: The programming paradigm is concerned with the data streams and the propagation of the change. It emphasizes asynchronous data handling and it is suited for applications that handle the large number of concurrent connections with minimal resource utilization.
- WebFilter: In the context of Spring WebFlux, the WebFilter is the interface used for the intercepting web requests and responses. It provides the capability to modify the incoming server requests and outgoing responses.
- Mono and Flux: These are the two core types in the Project Reactor. Mono can represent the single or empty asynchronous value. While Flux can represent the sequence of 0 to N asynchronous values.
- ServerWebExchange: The central class in the Spring WebFlux can represent the context of the HTTP exchange the request and the response. It allows for the modifications to the request and response and provides access to additional server-related information.
- Non-Blocking: Describes the mode of the operation that allows other processes to continue before the previous operation finishes, thus not blocking the execution thread.
- Back Pressure: The mechanism in reactive systems that allows the consumers to signal the producer about how much data they can process and it can preventing the consumer from being overwhelmed by the data sent by the producer.
- Event Loop: It handles the distribution of events across the different handlers and subscribers in a non-blocking fashion.
- Asynchronous: It allows the unit of work to run separately from the main application thread and notifies the calling thread of its completion, failure or progress.
Implementation of Intercept a Request and Add Headers in WebFlux
We will develop a simple spring reactive project that can intercept requests and modify their headers by implementing the WebFilter. This filter allows us to inspect and transform the requests throughout the application.
Step 1: Create the Spring Boot WebFlux Project
Create a new Spring Boot project using Spring Initializr and add the required dependencies as mentioned below,
- Spring Web Reactive
- Lombok
- Spring DevTools
After the project creation is done, the folder structure will be like below.
Step 2: Configure the Application properties
Open the application.properties file and add the configuration for the server port in the project.
server.port=8080
Step 3: Implement the WebFilter
We will create a new class that implements the WebFilter. In this filter, we will manipulate the ServerHttpRequest to add the custom header of the application.
Go to src > main > java > org.example.springheaderwebflux > config > HeaderAdditionFilter and put the below code.
Java
package org.example.springheaderwebflux.config;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Component
public class HeaderAdditionFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerWebExchange mutatedExchange = exchange.mutate()
.request(exchange.getRequest().mutate().header("Custom-Header", "CustomValue").build())
.build();
return chain.filter(mutatedExchange);
}
}
Step 4: Create the SampleController class
We will create a simple controller to demonstrate that the application is working.
Go to src > main > java > org.example.springheaderwebflux > controller > SampleController and put the below code.
Java
package org.example.springheaderwebflux.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class SampleController {
@GetMapping("/")
public Mono<String> hello() {
return Mono.just("Hello World!");
}
}
Step 5: Main Class
No changes are required in the main class.
Java
package org.example.springheaderwebflux;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringHeaderWebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(SpringHeaderWebfluxApplication.class, args);
}
}
Step 6: Run the application
Now, we will run the application and it will start at port 8080.

Endpoint Testing
Open the Postman tool and add the below request with the GET method and also add the custom header with header value then send the request.
GET http://localhost:8080/
Output:

This example project demonstrates how to Intercept a Request and Add Headers in WebFlux in the Spring Boot project.
Similar Reads
How to Redirect a Request in Spring WebFlux?
The Spring WebFlux is a part Spring Reactive framework. In Spring WebFlux, we can redirect requests by using the ServerResponse. This is one of the classes in Spring WebFlux which provides methods for creating responses. To direct a request in Spring WebFlux, we typically return the ServerResponse w
4 min read
How to Log Request and Response Bodies in Spring WebFlux?
To log request and response bodies in Spring WebFlux, we need to use filters or logging mechanisms that can intercept and log the necessary information. In this article, we use WebFilter to filter the request types in the Spring application. Intercepting the Request Body:The getRequest().getBody() m
5 min read
How to create a new request in Postman?
Postman is a development tool that is used for testing web APIs i.e. Application Programming Interfaces. It allows you to test the functionality of any application's APIs. Almost every developer uses Postman for testing purposes. We can create any type of HTTP request in it such as GET, POST, PUT, D
2 min read
How to set header request in Postman?
Postman is a powerful API development tool that offers a feature known as environment variables. These variables are used for efficient testing and development of APIs by allowing users to manage dynamic values across requests easily. In this article, we will learn How you can set header requests in
2 min read
How to Handle Logs and Tracing in Spring WebFlux?
In modern microservices, effective logging and tracing are essential for monitoring, debugging, and maintaining the applications. Spring Webflux is a reactive web framework and it can provide the tools and techniques for handling the logs and tracing efficiently. This article will guide you through
4 min read
How To Process Incoming Request Data in Flask
In this article, we will learn how we can use the request object in a flask to process Incoming request data that is passed to your routes and How To Process incoming Request Data in Flask using Python. Flask has some functionality like tools, libraries, and technologies that allow you to build a we
4 min read
How to add HTTP headers 'X-Frame-Options' on iframe ?
Inline frame tag in HTML: The iframe tag is used to displaying or embedding another document within an HTML document. One of its attributes 'src' is used to specify the URL of the document which is to be displayed. A site's X-frame Options can prevent allowing the display of one HTML document within
2 min read
Python requests - POST request with headers and body
HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.Request with headersRequests do not change its behavior at all based on wh
4 min read
How to create and send POST requests in Postman?
Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, and convert save the API to code for various languages(like JavaScript, and Python).
2 min read
How to Use Loading in Interceptor? - Angular 17
In Angular applications, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses. One common use case for interceptors is to display a loading indicator to the user while an HTTP request is in progress. This improves the user experience by providi
5 min read