1

I have a problem with getStaticProps in NextJS, i try to load specialists from API Route, but I get an error.

export const getStaticProps = async () => {
    const specialists = await loadSpecialists();

    return {
        props: { specialists },
    };
};

export const loadSpecialists = async () => {
    const response = await fetch('/api/specialists.js');
    const data = await response.json();

    return data;
};

if (req.method === 'GET') {
        const specialists = await database
            .collection('specialists')
            .find()
            .toArray();

        res.status(200).json({ specialists });
    }

I tried client-side rendering with useEffect and this works, but i need to prerender this page.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202

1 Answers1

0

Your url here

const response = await fetch('/api/specialists.js');

should be an absolute url. your client side code works because browser can handle the relative url

By default, the browser handles relative URLs in links by prepending the correct scheme (protocol), server name, and directory information (including the junction) to the relative URL. The browser derives the prepended information from the location information of the page on which the link is located.

When you are on server, server cannot know the origin. you either hardcode absolute url

export const loadSpecialists = async () => {
    // or you couldnt set in env variable
    const response = await fetch(“http://localhost:3000/api/specialists.js”);
    const data = await response.json();
    return data;
};
Yilmaz
  • 35,338
  • 10
  • 157
  • 202