Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 27, 2023 11:39
Show Gist options
  • Save ariesmcrae/7910fcb2e601f16ea7b1f92e6622e867 to your computer and use it in GitHub Desktop.
Save ariesmcrae/7910fcb2e601f16ea7b1f92e6622e867 to your computer and use it in GitHub Desktop.
Creating an Axios instance vs using Axios directly

Creating an Axios instance vs using Axios directly

TL;DR

It's preferable to create an Axios instance in node.js. Why? Because it offers several advantages over using Axios directly. It provides a more flexible, organized, and maintainable way to manage HTTP requests:

1. Custom Configuration

When you create an instance, you can set default configurations like base URL, headers, timeouts, etc., that will be applied to all requests made using that instance. This eliminates the need to specify these settings for each request.

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: {'Authorization': 'Bearer token'}
});

2. Reusability

Once you've created an Axios instance with a particular configuration, you can reuse it throughout your application. This makes the code more maintainable and easier to manage.

3. Multiple Instances

You can create multiple instances with different configurations. This is useful when interacting with multiple APIs that have different requirements.

const userAPI = axios.create({
  baseURL: 'https://user-api.example.com'
});

const productAPI = axios.create({
  baseURL: 'https://product-api.example.com'
});

4. Interceptors

You can define interceptors specifically for an instance, allowing you to handle request and response transformations, logging, or even redirecting under certain conditions.

instance.interceptors.request.use(config => {
  // Do something before request is sent
  return config;
}, error => {
  // Handle request error
  return Promise.reject(error);
});

5. Easier Testing

When you use instances, it's easier to write unit tests. You can mock a specific instance instead of the entire Axios library, making your tests more focused and easier to manage.

6. Code Organization

Using instances can lead to better code organization, especially in larger projects. You can create instances in separate modules and import them where needed, keeping your codebase clean and modular.

7. Instance-Specific Methods

You can also extend the Axios instance with custom methods, encapsulating related logic within the instance.

instance.customMethod = function() {
  // Custom logic here
};

8. Overriding Defaults

Even after creating an instance with default settings, you can still override those settings for individual requests if needed.

instance.get('/path', { timeout: 5000 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment