Enabling CORS in Micronaut using Filters

Enabling CORS in Micronaut using Filters

For a beginner CORS is a cross site resource sharing, Means when the request is sent from a browser, communication should happen with in the same domain. But now we are disturbing almost everything in this era, So there is always a chance that we might Host JS in one server and Backend in another. Or during  the development, JS code might run on different port/virtual host, During these scenario We get CORS error. there are multiple ways to Handel CORS. Either by using reverse Proxy server, or by enabling the  CORS in within the server. There is one line Configuration to do that in micronut by using :

            enabled: true

But  I am taking programmatic approach, and add small snippet of code which documents the concept of the filter, as this could be repurposed to anything like adding activity id for the request, and custom headers for all the response, or log both request and response. So now Lets dive into the Code snippet.

@Filter(value = "/**")
public class CorsAdvice  implements HttpServerFilter {

    public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
        return Flowable.fromCallable(() -> {
            return true;
        }).subscribeOn(Schedulers.io()).switchMap(a -> chain.proceed(request)).doOnNext(res -> {

Basically this uses http serverless filter to intercept the both request and response, we need to override the doFilter method to write our custom logic.

Do Filter method takes Http request , and ServerFliterChain as request, So to implement our logic we need to use RXJava Observable method  to subscribe. from callable method implement the preprocess logic if required, and  on Do next we can implement  Post process logic, in my example adding CORS headers.