1

I made an API route in the pages folder on a NextJS project. It works fine, I can fetch data from it by going to the URL directly such as http://localhost:3000/api/tv/popular. I want to fetch the data in getStaticProps and then forward to the components. It works fine if I do it this way

export const getStaticProps: GetStaticProps = async (ctx) => {
  const { data } = await axios.get("http://localhost:3000/api/tv/popular");

  return {
    props: {
      popularContent: data,
    },
  };
};

But if I remove local host and send request to axios.get("/api/tv/popular") it fails.

Why is this, I thought this should be possible in NextJs to not include localhost

itsDanial
  • 105
  • 1
  • 10
  • You should not call an internal API route inside `getStaticProps`. Instead, you can use your API logic directly in `getStaticProps`. See [Fetch error when building Next.js static website in production](https://stackoverflow.com/questions/66202840/fetch-error-when-building-next-js-static-website-in-production). – juliomalves Oct 02 '22 at 22:18
  • Whaaa, I have been doing that, and its been working for me so far. So what I've been doing is that in the API routes, I fetch data from a database, and external APIs, then reshape the data to fit my use case and then send that as a response. Afterwards, ill go to my page and just do one single fetch to routes in API folder with `getStaticProps` or `getServerSideProps`. Somehow I felt like this kept the code clean and somewhat separated me from having to look at backend code and front-end code in the same file. I don't seem to have any of the problems mentioned in this other post – itsDanial Oct 03 '22 at 11:22
  • Try building the app and running it in production mode (`next build && next start`). You can still separate the backend logic into different files if you so wish. – juliomalves Oct 03 '22 at 11:38
  • It seems to be working without any issue, I checked the logs, [link](https://watched-this.vercel.app/) but basically what you're saying is that its wrong practice to call the internal API from `getStaticProps` or `getServerSideProps` – itsDanial Oct 03 '22 at 11:45

1 Answers1

2

As per API concept, it has to come from a server correct? Hence Nextjs gives the same server where it runs. Hence you have to use localhost:3000 or any port you give

In future it will be a problem for you while production. Hence use .env file

NEXT_PUBLIC_BASE_URL = http://localhost:3000

and use it in your api calls whenever you go for production you can change the same.

Hope it clarifies something.

  • ah smart, thanks, man. I thought NextJS automatically detects the URL part before /api cause the same server is being used for front and back – itsDanial Sep 28 '22 at 08:59