Fetch Data From API | Next.js | getServerSideProps


How to fetch data from an API in Next.js Page on Request?

getServerSideProps can be used to fetch data in Next.js in server side and pass it on to the page during render.

Define getServerSideProps method inside the next.js page. Inside this method what ever you do will get executed only on server side and not on browser.

getServerSideProps method gets executed whenever the page is requested and data is passed as props to the Page component.

export default function Brands({data}:{data:any}) {
  return (
    <>
      <h3>
        Welcome to Brands !! {data[0]['title']}
      </h3>
    </>
  )
}

export async function getServerSideProps(context:any) {
  // ## fetch data from API
  let data = await fetch('https://jsonplaceholder.typicode.com/todos/')
              .then(response => response.json())
  // ## pass data to the page component as props
  return {
    props: {data}, 
  }
}