This is a premium alert message you can set from Layout! Get Now!

getInitialProps vs. getServerSideProps in Next.js

0

Among the changes included with Next.js v9.3 was the introduction of getServerSideProps. When it came to defining props for pages rendered on the server side, getServerSideProps essentially replaced getInitialProps.

Nowadays, some developers occasionally run into confusion about which method to use. In this article, we’ll explore how getServerSideProps and getInitialProps work, reviewing an example for each. Let’s get started!

Inner workings of getServerSideProps and getStaticProps

Essentially, if you need to render a page at build time before making any request, then you’d use getStaticProps. getStaticProps will mark the page to be statically rendered, meaning it won’t re-render until the next build. While this methodology is great for speed and SEO, it isn’t great for dynamic data that changes regularly.

If you want to render a page at the time of the request, you can use getServerSideProps to render a page on the server before responding to a request. getServerSideProps will mark the page to be rendered on each request. In this method, the server will have to build the page every time, which can slow down the entire process. However, this methodology still offers SEO benefits over using plain Vanilla React, which would render your content on the client.

Next Getserversideprops Getstaticprops Diagram

The thing about updates to languages and frameworks is that backward compatibility matters. Even if old patterns and methods are no longer needed for future projects, they are still maintained to avoid breaking legacy code and for the occasional edge cases. This is the case of getInitialProps, which behaves almost identical to getServerSideProps.

Is there a difference between getInitialProps and getServerSideProps?

The main difference between the legacy getInitialProps and the newer getServerSideProps is how the function is used during transitions, when users click on a Link to visit different parts of your site.

With getInitialProps, the transition will execute server-side on the initial page load, but then execute on the client during page transitions. However, if the logic refers to things like databases, which may not be accessible on the client, this can create issues.

For example, in the code snippet below, the fetch of the users directly from the database would work on the initial page load. However, it may fail on transitions since the User model would not be available on the client.

As a solution, we could use Next.js API endpoints. However, this is a less efficient method than directly accessing the database on the server side:

// Import a User model
import User from "../models/User"
function Page({ User }) {
    return <div>Username: {User.username}</div>
  }

  Page.getInitialProps = async (ctx) => {
    // Get user id
    const User = await User.findOne(ctx.query.id)
    // return props
    return {
        User
    }
  }

  export default Page

On the other hand, getServerSideProps will execute the transitions server-side on the initial page load. On the page transition, getServerSideProps will make an API call to the server, running the logic again on the server and returning the results as JSON.

By making this change, we fix the problem of context switching that occurs with getInitialProps. In the example below, you can make a direct call to the database, and it will work fine on initial page load and on transitions:

// Import a User model
import User from "../models/User"
function Page({ User }) {
    return <div>Username: {User.username}</div>
  }
  export async function getServerSideProps(context) {
    // Get user id
    const User = await User.findOne(ctx.query.id)
    return {
      props: {User}, // will be passed to the page component as props
    }
  } 

  export default Page

Which one should you use?

If you’re creating newer Next.js applications, there is probably no reason to use legacy methods like getInitialProps because getServerSideProps and getStaticProps provide better functionality and semantics.

In this article, we clarified the differences between getServerSideProps and getInitialProps, looking at an example of how we can solve context switching in getInitialProps with getServerSideProps.

I hope you enjoyed this article, and if you have any questions, please leave a comment. To learn more about Next.js and other meta frameworks, be sure to check out this article comparing Next.js and Remix.

The post <code>getInitialProps</code> vs. <code>getServerSideProps</code> in Next.js appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/ynMusJK
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top