Don’t hesitate to contact us if you have any feedback.

Javascript – Intercept Fetch Requests

Modern web applications often rely on asynchronous HTTP requests (commonly known as Ajax requests) to communicate with servers without needing to reload the page. This JavaScript code snippet provides a mechanism to intercept and handle fetch requests globally, allowing developers to execute custom logic at various stages of the request lifecycle.

The Code

window.fetchIntercept = {};

window.fetchIntercept.ajaxStart = (args) => {
  console.log('do something when an ajax fetch request start');
};
window.fetchIntercept.ajaxStop = (args) => {
  console.log('do something when an ajax fetch request end');
};
window.fetchIntercept.ajaxError = (args) => {
  console.log('do something when an ajax fetch request fail');
};

const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
  const [resource, config] = args;

  // Catch when ajax starts
  window.fetchIntercept.ajaxStart(args);

  try {
    const response = await originalFetch(resource, config);

    // Catch when ajax sends a response
    window.fetchIntercept.ajaxStop(args);

    // Catch when ajax returns an error
    if (!response.ok) {
      window.fetchIntercept.ajaxError(args);
    }

    return response;
  } catch (error) {
    // Catch network errors or other fetch errors
    window.fetchIntercept.ajaxError(args);
    throw error;
  }
};

How It Functions

The script overrides the native window.fetch function with a custom implementation that:

  1. Invokes ajaxStart before initiating the fetch request.
  2. Awaits the response from the original fetch call.
  3. Invokes ajaxStop after receiving the response.
  4. Checks if the response was unsuccessful (e.g., 404 error) and invokes ajaxError.
  5. Re-throws any caught errors to ensure error handling remains consistent.

Usage Scenarios

This fetch intercept can be used for:

  • Global Loading Indicators: Show or hide a loading spinner when any fetch request starts or ends.
  • Error Logging: Log errors to a central system when a fetch request fails.
  • Analytics and Monitoring: Track the start and end of fetch requests for performance monitoring.

Advantages

  • Centralized Control: Manage all fetch requests from a single place in your codebase.
  • Customization: Easily tailor the behavior of fetch requests across your application.
  • Debugging: Simplify debugging by logging all fetch interactions.

By including this fetch intercept in your web application, you gain the ability to execute custom logic at different stages of making HTTP requests, providing you with greater control over the behavior of your application’s data fetching strategies.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *