Nextjs Data fetching methods

Coming from CRA, there were many new concepts that I wasn’t very familiar with in Nextjs. One of them was Data fetching methods. There is a whole page about this feature in their docs but even after reading it a couple of times, I still couldn’t understand the differences. I did some research about it and here is my summary.
getServerSideProps
getServerSideProps method fetches data on each request, meaning on every page refresh, Nextjs will run getServerSideProps. So if you have a query in this method, the query will run on every page refresh. However, it can be a bit wasteful if your data doesn’t change often. For that reason, Nextjs also provides a static generation method, getStaticProps
getStaticProps
getStaticProps fetches data at build time. It fetches data in advance and pre-loads the data so it’s really fast. But be careful, if you are running this method in dev mode, it will just run like the getServerSideProps method. To see the differences you should run npm run start
instead if you are running npm run dev. If you run npm run start
, new data added after build time won’t be rendered.
But what if you need to update your data every once in a while? That’s where a return parameter, revalidate comes in. You can add revalidate field in the return object to tell Nextjs how often you want to update your data. By adding revalidate, you can sort of keep the benefit of getServerSideProps and getStaticProps. You can benefit from getting the latest data from your backend and from a faster page load by pre-fetching data.
getStaticPaths
With getStaticPaths method, you can tell Nextjs which dynamic route you want to pre-load and pre-create pages for. If you have five blog posts in your database, then Nextjs will create 5 blog post pages in advance.
You can check this by running thenext export
command. Then in a folder called out
, you can see statically generated pages.
getStaticPaths method must return an object field calledfallback
which takes a boolean value. It tells you what to do if a page is not rendered at build time. So if fallback is true, Nextjs will try to render the page at request time. But if it’s false, it will show you a 404 page. Therefore, if you setfallback
to false, newly added blog posts to your database after build time won’t be rendered.
To summarise, we should use getSeverSideProps if a real-time, up to date data is what we are looking for. But if our database doesn’t get updated very often, for better performance, we better opt for these static methods.
Thank you for reading and happy coding :)