fetch-request-interceptor
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Fetch Interceptor

Fetch Interceptor is an npm library that allows you to modify, enhance, and inspect HTTP requests and responses made using the Fetch API. It supports adding headers, handling errors, and chaining multiple interceptors for sophisticated request/response handling.

Install

$ npm install --save fetch-request-interceptor

Usage

import {useEffect} from 'react'
import { createFetchInterceptor } from 'fetch-request-interceptor';

function App() {
  
  useEffect(() => {

	const jwt = localStorage.getItem('jwt')
    const interceptor = createFetchInterceptor();
    interceptor.setRequestInterceptor(async (input, init = {}) => {
      // Ensure init is defined and headers object is initialized
      init.headers = {
        ...init.headers, // Preserve any existing headers
        Authorization:
          `Bearer ${jwt}`,
        // If you want to override any header do here...
      };

      console.log('Intercepted request:', input, init);

      return { input, init };
    });

    fetch('https://jsonplaceholder.typicode.com/todos/1', {
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((response) => response.json())
      .then((data) => console.log({ data }));
  }, []);
  return <div>React fetch interceptor</div>
}

👨🏻‍💻 AUTHOR

Abdul Rehman

Package Sidebar

Install

npm i fetch-request-interceptor

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

8.53 kB

Total Files

9

Last publish

Collaborators

  • abdul-rehman-12