The `create()` Function in Axios

Sep 18, 2019

The axios.create() function creates a new Axios instance. When you require('axios'), you get back an the default Axios instance. The reason why you would create an instance is to set custom defaults for your application.

For example, suppose you wanted to add a timeout to all your Axios requests. You could create a new Axios instance with a default timeout of 1000 milliseconds:

const axios = require('axios');
const instance = axios.create({ timeout: 1000 });

// `instance` is an instance of the same class as `axios`, so it has
// the same methods
axios.constructor === instance.constructor; // true

// For example, `instance.get()` lets you send a GET request, but
// it will also have the 1000ms timeout.
await instance.get('https://httpbin.org/get?hello=world');

Another common use case is setting the baseURL for all requests. This is convenient so you don't have to type out the absolute URL every time.

const axios = require('axios').create({
  baseURL: 'https://httpbin.org'
});

// Sends request to 'https://httpbin.org/get' 
const res = await axios.get('/get?hello=world');

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!