DEV Community

Ashutosh
Ashutosh

Posted on

4 3

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'
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay