I need to fetch data with a third-party API in some of my components in the NextJS project
I want the server to pre-render the component using that API for SEO.
but after that while user is interacting with the app, the component props should fetch on the client-side.
I’m able to implement this behavior by using NextJS getInitialProps
method. but in official NextJS documentation it’s recommended to use getStaticProps
or getServerSideProps
.
I want to know What is the recommended way to do this.
3
Answers
Bundle size is smaller when we use getServerSideProps instead of getInitialProps as the getServerSideProps execute the code on the server not on the browser.
Read more about the difference between these two here.
Next.js docs says:
You should use getStaticProps if:
If you already know how many pages your website will contain then go with Static Site Generation i.e use
getStaticProps
. This will pre-generate all the pages in advance during build time.Example A portfolio website where the content is mostly static.
NOTE:- With getStaticProps any changes made to your website won’t be reflected you need to re-deploy in order to see the changes.
So if your portfolio also consists of a blog then
getStaticProps
won’t be an ideal solution, instead you can use Incremental Static Regeneration by adding a revalidate key in thegetStaticProps
function which implies that re-generate the page on every request at most every X-seconds.Now if you need to pre-render for every request OR you need access to request object for example to set cookies then Server Side Rendering is an option use
getServerSideProps
function. getServerSideProps runs only on the server and not during the build processFor client side data fetching you can use the useEffect hook or the swr hook provided by NEXT JS.
So in your case,
If you are using client side data fetching then probably it doesn’t make any sense to use
getServerSideProps
in conjunction, unless you need that request response object.So you can combine Client Side Data Fetching with getStaticProps (most probably with that revalidate key).