How to fetch API data from Axios inside the getServerSideProps function in NextJS? How to fetch API data from Axios inside the getServerSideProps function in NextJS? reactjs reactjs

How to fetch API data from Axios inside the getServerSideProps function in NextJS?


Do not use Axios. Just use fetch().

Next.js polyfills fetch() by default on both the client and server, so you can just use it:

In addition to fetch() on the client-side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() in your server code (such as getStaticProps/getServerSideProps) without using polyfills such as isomorphic-unfetch or node-fetch.

Source.


You are not using the jwtToken for anything after passing it to the service.

Before the line const instance = axios.create(options); add something like this:

if (jwtToken !== null) {  options.headers.Authorization = `Bearer ${jwtToken}`}


Your problem is that your async method does not return a promise.

import service from '../service'export const getAllAccounts = async (adminToken) => {  const res = service({ jwtToken : adminToken }).get(`/accounts`);  return res;}