Fetch vs Axios

Nowadays, there are two popular options for making HTTP requests in Javascript (and React Native) are the built-in fetch API and the third-party library axios. 

Both have their strengths and weaknesses, so in this blog, we will compare fetch and axios to make an informed choice.

1. Fetch

Fetch is a native Javascript function - promise-based API for making HTTP requests. It's build into the browser and doesn't require any additional libraries (via polyfills)
Ex: 

2. Axios

- Axios is a popular third-party library for making HTTP requests. It is also a promise-based HTTP client for the browser and Node.js. 

- It provides a simpler, more feature-rich API compared to fetch and is widely used in React/React Native applications.
Ex: 

3. Error handling

- Fetch: Requires manual handling of HTTP errors. It doesn't throw an HTTP errors like 404, 500 and fetch only rejects the promise on network errors. So you need to check response.ok property to determine if the request was successful or not.
Ex:


- Axios:  Automatically rejects the promise for HTTP errors that means it throws an error for HTTP errors. You get more detailed error object with response, request, and message properties. You can handle it in try/catch block or with .catch()
Ex: 

4. Request and response interceptors

- Fetch: doesn't support interceptors natively. You would need to implement your own logic to modify requests or response before they are sent or received.
Ex:


- Axios: provides built-in interceptors for both requests and responses. 
Ex: 

5. JSON data transformation

- Fetch: doesn't automatically parse the response into JSON. It requires explicit conversion to JSON using response.json(), which returns a promise.
Ex: 

- Axios: automatically transforms the response body based on the Content-Type header, so you don't need to call response.json() manually. You can access response.data directly.
Ex: 

6. Request cancel

- Fetch: doesn't natively support request cancellation, but it can be combined with AbortController to cancel request.
Ex:

- Axios: has built-in support for request cancellation using CancelToken.
Ex: 

7. Additional features in axios

- Automatic request timeout: axios allow you to set an automatic timeout for request.
Ex: 

- Response schema: axios provides the full response schema with detailed information, including status, headers, data, etc
Ex:

8. Comparison summary

Both fetch and axios are capable tools for making API requests. Your choice depends on your specific needs:
- Choose fetch if you prefer using a built-in lightweight solution and are comfortable handling HTTP errors and request/response transformations manually.
- Choose axios if you need a feature-rich library with built-in support for interceptors, automatic JSON parsing, request cancellation, etc


9. Reference

Geeksforgeeks. (2025, April 15). Difference between Fetch and Axios for Making HTTP Requests



Post a Comment

0 Comments