Introduction to Next.js Introduction to Next.js

Building Dynamic Pages with getServerSideProps

Check out a free preview of the full Introduction to Next.js course:
The "Building Dynamic Pages with getServerSideProps" Lesson is part of the full, Introduction to Next.js course featured in this preview video. Here's what you'd learn in this lesson:

Scott explains that the getServerSideProps function is similar to the handlers used in similar functions, but is used within a page, and refactors code using getServerSideProps.

Get Unlimited Access Now

Transcript from the "Building Dynamic Pages with getServerSideProps" Lesson

[00:00:00]
>> Now, we're gonna talk about getServerSideProps. So, getServerSideProps is really simple, you can think of it as the API handlers that we've been working on but inside your page. At the end of the day, that's kind of basically what it is. So, you get access to the request and the response objects inside of here, you get access to all that stuff.

[00:00:17] You can do whatever you want that's valid on the server. Very much like getStaticProps, you just need to return an object with props. That's it, and that's gonna be passing to your component. The difference between this and getStaticProps is that this function, getServerSideProps, is always executed per request.

[00:00:34] So when you hit this request, it's gonna run this function. Whereas getStaticProps only happens once at build time, getSeverSideProps happens every time on the request. So it's true server side rendering. And so this might be a better place to put something dynamic like a user ID, where you don't want to generate every single user ahead of time, which is ridiculous.

[00:00:54] And instead, you just wanna render them when they're asked on the server. Or even better, just do it on the client, use an SWR or react query, and don't do anything on the server. Just render the HT, just render the JSX, and do the data fetching on the client.

[00:01:06] So those would be better alternatives. But yeah, that's basically it. And like I said, you get access to the request and response objects, which we will be using in the next example. And yeah, it's really powerful.