Onjsdev

Share


Axios Instance vs Axios Request Config Defaults


By onjsdev

Feb 12th, 2024

The Axios instance and Axios request config defaults are similar concepts, but they have slight differences. Let's break down each concept and explore their distinctions.

Axios Instance

An Axios instance is a customized version of the axios object, which is created using the axios.create() method. An Axios instance allows us to set default configuration options for all requests made through that instance.

// Import Axios library
import axios from 'axios';

// Create an Axios instance with default configuration
const instance = axios.create({
  baseURL: 'https://api.example.com', // Set a base URL for all requests
  timeout: 5000, // Set a timeout for requests in milliseconds
  headers: {
    'Content-Type': 'application/json', // Set default headers for all requests
    'Authorization': 'Bearer YourAccessToken', // Set default authorization header
  },
});

// Now, you can use 'instance' for making requests with the configured defaults

// Making a GET request using the Axios instance
instance.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Using an Axios Instance is particularly useful when you want to reuse common settings across multiple requests.

Axios Request Config Defaults

On the other hand, Axios request config defaults are global default configurations applied to all Axios requests. These defaults are set using axios.defaults and are applied to every Axios request made throughout your application.

// Set global defaults for Axios requests
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
axios.defaults.headers.common['Authorization'] = 'Bearer YourAccessToken';

// Making a GET request using Axios with defaults
axios.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Axios request config defaults can be convenient when you want to apply the same configuration options globally across your application without creating specific instances.

Conclusion

In summary, Axios instances are useful for creating customized configurations for specific sets of requests, while Axios request config defaults allow you to set global defaults for all Axios requests in your application.

Thank you for readind.