Category: Axios

  • How to improve the performance of your Axios API requests

    There are two simple changes you need to make in order to drastically improve Axios performance:

    • Don’t create the HTTP agent for every request
    • Enable HTTP Keep-Alive

    The Axios docs show that when using a request config you should specify agents like this:

    //...
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),
    //...

    But of course, this means you’re creating two new agents for every request.

    Instead you should make an Axios Helpers file which imports Axios, sets the defaults, and then exports Axios:

    //axios_helpers.ts
    
    import axios from 'axios'
    
    import https from 'https'
    
    const agent = new https.Agent({
        keepAlive: true
    })
    
    axios.defaults.httpsAgent = agent
    
    export default axios

    and where ever you use axios, you should import it from this file so that the default agent is set, and HTTP Keep-Alive is enabled.

    // page.tsx
    
    //before
    
    import axios from 'axios'
    
    //after
    
    import axios from '../utils/axios_helpers'