Skip to main content

Axios vs Fetch API in JavaScript – Everything You Need to Know

Axios vs Fetch API in JavaScript – Everything You Need to Know

When building web apps, you often need to fetch data from APIs or send data to a server. In JavaScript, two popular ways to make HTTP requests are Fetch API and Axios. But which one should you use? In this guide, we’ll break it down with examples, pros and cons, features, and real-life use cases.

๐Ÿ” What is Fetch API?

Fetch API is a built-in browser feature that allows you to make HTTP requests. It returns Promises and is supported in all modern browsers.

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
  

⚙️ What is Axios?

Axios is a third-party JavaScript library built on top of XMLHttpRequest. It provides a clean API for sending HTTP requests and handling responses.

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
  

๐Ÿ“Š Syntax Comparison

POST Request

// Fetch
fetch('/api/user', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'John' })
})
.then(res => res.json())
.then(data => console.log(data));

// Axios
axios.post('/api/user', { name: 'John' })
  .then(res => console.log(res.data));
  

๐Ÿ“‹ Feature Comparison Table

Feature Fetch Axios
Built-in Yes No (needs install)
JSON Auto Parsing No Yes
Request Cancellation AbortController axios.CancelToken
Request Timeout No Yes
Interceptors No Yes
Node.js Support Yes (with node-fetch) Yes
Response Schema Basic Rich (status, headers, config)

✅ Pros and Cons

Axios Pros

  • Easy syntax
  • Built-in JSON parsing
  • Timeout support
  • Interceptors for auth headers

Axios Cons

  • Extra dependency
  • Heavier bundle size

Fetch Pros

  • No installation required
  • Lightweight
  • More control

Fetch Cons

  • Verbose error handling
  • No timeout or interceptors by default

๐Ÿšซ Error Handling Difference

Fetch does not throw on HTTP errors (like 404), while Axios does.

// Fetch
fetch('/api')
  .then(res => {
    if (!res.ok) throw new Error('Failed');
    return res.json();
  })
  .catch(err => console.error(err));

// Axios
axios.get('/api')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));
  

๐Ÿงพ JSON Handling

With Fetch, you must manually call res.json(). Axios auto-converts JSON.

๐Ÿ“ค File Upload Example

// Using Axios
const formData = new FormData();
formData.append('file', fileInput.files[0]);

axios.post('/upload', formData)
  .then(res => console.log(res));
  

๐Ÿ›‘ Canceling Requests

// Axios cancel token
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/data', { cancelToken: source.token })
  .catch(thrown => {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled', thrown.message);
    }
  });

source.cancel('Operation canceled by the user.');
  

๐Ÿงฉ Interceptors in Axios

Used to attach tokens, log requests, or modify headers globally.

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer token';
  return config;
});
  

๐Ÿš€ Performance

Fetch is slightly faster due to being native and lighter. Axios may add milliseconds due to extra parsing and features.

๐ŸŽฏ When to Use What

  • Use Fetch: Small apps, fewer dependencies, full control
  • Use Axios: Complex apps, interceptors, automatic parsing

๐Ÿ“Œ Final Verdict

If you want simplicity and zero config, go with Fetch. If you prefer developer comfort, advanced features, and clean syntax — Axios is a great choice.

Thanks for reading! Let me know in the comments — are you Team Axios or Team Fetch?

Happy coding! ๐Ÿง ๐Ÿ“ก

Comments

Popular posts from this blog

How to Display Flash Messages in EJS using Node.js and Express

Displaying Flash Messages in EJS with Node.js and Express Flash messages are a great way to give users quick feedback — like "Login successful!" or "Please enter all fields!" . In this guide, you’ll learn how to implement them using: express-session connect-flash EJS templating ๐Ÿ“ฆ Step 1: Install Required Packages npm install express express-session connect-flash ejs ⚙️ Step 2: Setup Express App and Middleware const express = require('express'); const session = require('express-session'); const flash = require('connect-flash'); const app = express(); // Set view engine app.set('view engine', 'ejs'); // Middleware app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'yourSecretKey', resave: false, saveUninitialized: true })); app.use(flash()); // Make flash messages available to all views app.use((req, res, next) => { res.lo...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...

How to Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...