0

I am using getServerSideProps to make backend request for data

export async function getServerSideProps(context) {
    const res = await MachineService.listOrgs()
    const organizatons = [
        'csdc3443dsvk',
        'csddscd3443dsvk',
        '12dc3443dsvk',
        'csdc3443ds56k',
        'csdc3443ds67',
    ]
    return {
        props: { organizatons }, // will be passed to the page component as props
    }
}

Here is my listOrgs code

const listOrgs = async (nextToken, limit) => {
    return new Promise(async (resolve, reject) => {
        fetch('http://localhost:3000/api/organizations/')
            .then(res => res.json())
            .then((result) => {
                resolve({ Organizations: result })
            })
            .catch((error) => reject(error))
    });
}
export default listOrgs;

This is the error enter image description here

making request to http://localhost:3000/api/organizations/ from browser returns me expected data but calling it from server side returns above error

  • Is `/api/organizations` an internal Next.js API route? If so, you shouldn't call an internal API route from `getServerSideProps`, instead use the API logic directly. See [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/questions/65752932/internal-api-fetch-with-getserversideprops-next-js). – juliomalves Jun 25 '22 at 15:31

1 Answers1

1

Because fetch is only work on browser (client side), getServerSideProps run in server side (Nodejs) so your code is not working. You can try axios or isomorphic-fetch, these methods running on both server and client environment

iamhuynq
  • 5,357
  • 1
  • 13
  • 36
  • 1
    In Next.js, `fetch` gets polyfilled with `node-fetch` on the server-side. It's perfectly fine to use `fetch` in `getServerSideProps`. See [Is fetch inside getStaticProps and getServerSideProps the same as the native browser fetch API?](https://stackoverflow.com/questions/68795872/is-fetch-inside-getstaticprops-and-getserversideprops-the-same-as-the-native-bro). – juliomalves Jun 25 '22 at 15:29