Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

How can I intercept the request coming from frontend UI to certain endpoint and how can I intercept the response of that endpoint which our backend controller is sending to frontend?

To intercept requests and responses between the frontend (ReactJS) and backend (Spring Boot), follow these steps:


Intercepting Requests from ReactJS

1: In ReactJS, you can use tools like Axios interceptors or Fetch wrappers.

2: How to do it with Axios -

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  return config;
}, function (error) {
  return Promise.reject(error);
});


Intercepting Responses in ReactJS

With Axios -

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  return Promise.reject(error);
});


Intercepting Requests and Responses in Spring Boot

1: In Spring Boot, use a Filter or HandlerInterceptor.

2: Example using HandlerInterceptor -

public class CustomInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                  HttpServletResponse response, Object handler) {
        // This runs before controller (intercept request)
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, 
           HttpServletResponse response, Object handler, 
                                  ModelAndView modelAndView) {
        // This runs after controller (intercept response)
    }
}

3: Register the interceptor -

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor());
    }
}


Summary:

1: Use Axios interceptors in ReactJS to catch requests/responses on the frontend.

2: Use HandlerInterceptor (or Filter) in Spring Boot to intercept requests/responses on the backend.


This approach is simple and works for most SpringBoot-ReactJS applications!

Ready for commit