-1

How can i write a function to call an API, from web server to API within the server itself. I do not want the browser to know that he is calling an API or and information about the API, even the link. The API call(POST method) should be executed on the server.

Using Nextjs with axios. I also want the function to be a component.

  • Please provide enough code so others can better understand or reproduce the problem. – Community May 31 '22 at 01:35
  • Do you mean you want to call an internal API route from `getStaticProps`/`getServerSideProps`? If so, you shouldn't do that, see [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/questions/65752932/internal-api-fetch-with-getserversideprops-next-js). – juliomalves Jun 01 '22 at 17:33

1 Answers1

0

If you want to fetch data before loading the page (when the actural page load request happens), use server side rendering.

In Next.js you can use getServerSideProps for doing this. By doing this, you get to keep the api call inside the component, and the sever will fetch the data before rendering your component. Attaching a sample of code that you can refer for this.

export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

For more info, please visit the nextjs official documents. Attaching a link for the above example.

https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

Demolition
  • 138
  • 1
  • 1
  • 10