How to fetch data server side in Next.js
In this post, we will see how to fetch the data server-side in next.js
To fetch data, we need to use getStaticProps() lifecycle method.
Installing package
To make fetch requests we use isomorphic-unfetch. To install this package run below command
yarn add isomorphic-unfetch
Now add below code in the component you want to fetch data. This is similar to react's useEffect() hook. This will fetch the data only once and stores it in the cache.
import fetch from 'isomorphic-unfetch'
function Posts({ data }) {
return (
<ul>
{data.map((d) => (
<li>{d.title}</li>
))}
</ul>
)
}
export async function getStaticProps() {
const res = await fetch('https://localhost:5000/posts')
const data = await res.json()
return {
props: {
data,
},
}
}
export default Posts
the getStaticProps will run on the server-side and returns the data to the component.
If you want to fetch data on every request use getServerSideProps