title: How to fetch API data from Axios inside the getServerSideProps function in NextJS?
body: <p>I'm building an App with Next.js, and I need to connect to specific API routes (set up with <a href="https://api-platform.com" rel="noreferrer">API Platform</a>) and populate pages with the route's responses.</p>
  <p>The API is working fine, but no matter how I try to implement my Axios call inside the <code>getServerSideProps</code>, I always get the same error, <code>ECONNREFUSED</code>, from my Node stack.</p>
  <p>I tried to get the data from <code>useEffect()</code> and it's working fine, but I would like to know if there's a way to call it directly in <code>getServerSideProps</code>.</p>
  <p>I'm using a Node container for Docker, and the routes are authenticated through a JWT Token (stored in the session and the client cookies for the server-side connection)</p>
  <p>Here are is my code:</p>
  <p><code>pages/accounts.js</code>:</p>
  <pre class="lang-js prettyprint-override"><code>export async function getServerSideProps(context) {
    const cookies = new Cookies(context.req.headers.cookie)
    const adminToken = cookies.get('jwtToken')
  
    const res = await getAllAccounts(adminToken)
  
    return {
      props: {
        testdata: ''
      },
    }
  }
  </code></pre>
  <p><code>lib/accounts.js</code>:</p>
  <pre class="lang-js prettyprint-override"><code>import service from '../service'
  
  export const getAllAccounts = async (adminToken) =&gt; {
    const res = service({ jwtToken : adminToken }).get(`/accounts`).then((response) =&gt; {
    
    }).catch((error) =&gt; {
      console.dir(error)
    })
  }
  </code></pre>
  <p>HTTP wrapper:</p>
  <pre class="lang-js prettyprint-override"><code>import axios from 'axios';
  import jwt_decode from &quot;jwt-decode&quot;;
  import mockAdapter from 'axios-mock-adapter';
  
  const service = ({ jwtToken = null, store = null, mockURL = null, mockResponse = null, multipart = false } = {}) =&gt; {
    const options = {};
  
    options.baseURL = process.env.NEXT_PUBLIC_API_URL + '/api';
  
    if(multipart === true) {
      options.headers = {
        'Content-Type': 'multipart/form-data'
      }
    } else {
      options.headers = {
        'Content-Type': 'application/ld+json',
        accept: 'application/ld+json'
      }
    }
  
    const instance = axios.create(options);
  
    instance.interceptors.response.use(response =&gt; {
      return response;
    }, error =&gt; {
      return Promise.reject(error);
    })
  
    if (mockURL !== null &amp;&amp; mockResponse !== null) {
      let mock = new mockAdapter(instance);
      mock.onAny(mockURL).reply(200, mockResponse)
    }
  
    return instance;
  };
  
  export default service;
  </code></pre>
  <p>Through the error dump in the node stack, I managed to see that the request headers are correct, and the JWT correctly passed through.</p>