Howdy NextJS getServerSideProps()?

In Next.js, There are two ways to pre-render a page:

  • Static
  • Server-Side Pre-rendering

We already cover static pre-rendering in our earlier articles. In this section, we cover how to generate pages on the server-side in Next.js.

Most of the time, you don't need to generate pages on the server-side. Static generation serves the purpose for us. But sometimes, static generation is not enough when we want to access an object or, let's say, cookies or session, etc.

A perfect example of this scenario is the user details page. Why? Because we don't know which user is sending the request to his/her details from the server. Hence it is unlikely to pre-render the user details page.

function UserProfilePage(props) {
    return (
        <div>
            <div>
                Username: <span>{props.userFullName}</span>
            </div>
            <div>
                 Email: <span>{props.userEmail}</span>
            </div>
        </div>
    )
}
export default UserProfilePage
export async function getServerSideProps(context){
    // Default Node objects. If you change it to request and response. It will not work
    const { params, req, res } = context 
    // console.log(req)
    // console.log(res)
    return {
        props:{
            userFullName: 'Michael Foo',
            userEmail: 'michael@example.com'
        }
    }
}

Go to the browser and visit http://localhost:3000/profile

The function getServerSideProps() not called when the app builds. However, it's called for every incoming request to the server.

Not only this, but in getServerSideProps(), we also get access to the request (to be precise req) and response (res).

You can try removing the comments in the console.log lines in the code.

Last but not the least, just run "yarn build" and observe the messages during the generation of the build.

Refer the attached image for details.