Next.js 9.3+ Data Fetching Explained: getServerSideProps(), getStaticProps(), and getStaticPaths()

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there are you building a nexjs application and need to understand its data fetching capabilities better if so you've come to the right place my name is otto and in this video we're going to take a look at nexjs's static generation and server-side rendering capabilities as well as learn when and how to use these strategies in building our applications let's dive right in all right so let's get started here i am on the next js homepage and i'm quickly going to go to the docs and data fetching section and take a look at the three new methods that were introduced back in nexus version 9.3 if you're using a prior version like next js 9.2 and below you might be familiar with another method for static and server side rendering called get initial props and that method is on its way to being deprecated and not used anymore and the next.js team recommends using one of these three new methods and the three new methods introduced are get static props get static paths and get server side props now the first two are used for static static page generation and the last one is used for server side render and i think it makes more sense to take a look at the server-side rendering method first because it's a little bit easier to conceptualize and it might be something that you're already familiar with so the get server side props method is going to fetch data on every single request we make so every single time we refresh the page the getserversideprops method is going to be activated it's going to run get our data and feed it to our component and we would use this method on any page within our next.js application that needed to get data before rendering the component now for the example application rather than starting from scratch what i think i'll use is an application that a good friend of mine ryan chanky and i have been working on uh called speak.dev so i already have a repo up and running here with a bunch of different pages a bunch of different features and functionalities and in this video we're just going to focus on how we can use this application and how we can use the data fetching capabilities of the next.js framework and what we're going to focus on is this events directory right here which is in our pages directory and it has two different files uh index which is going to be the main page that gets loaded up when we run our application and then this brackets id page which is going to be the dynamic page for an individual event that is going to be fed dynamically based on the route that we provide so if we open up this index.tsx file we see that is just going to render some data based on an events prop that we pass into it we're not doing anything fancy here we are just rendering some data and the way that we're going to populate that props element is using our get server side props next.js method and you can see here on line 48 we are running export async function getserver sideprops and then we are getting our data from a graphql helper that i've written and if we take a look at the query here we're going to go into our database get our events and then just get the id the name and the url of the event and then that data is going to be populated onto our props.events object and then sent into our events component so if i start this application i'll say npm run start that's going to take a couple of seconds once our server has started we'll be able to navigate into localhost 3000 forward slash events and we're going to see our events and currently we have one two three four five six events now when it comes to the get server side props method this method is going to run every time we refresh the page so on every page load on every page refresh this get server side props method is going to run it's going to make this database this graphql call to our database populate it and then render the date and we can see that here we have our elements and everything works great and then if we click into any of them so let's say ngcom for example here we see the events and then the id for it so the unique identifier and that's going to load up our and that's going to load up our specific event information now let's take a look at where our data is coming from uh all of the data is coming from mongodb so i have a mongodb database set up on mongodb atlas with this collection with this database called speak.dev this events collection and then here is our list of events so because every single time we render this page we make a call to our database if we were to make an update let's say we wanted to rename one of the events so let's say ngcom 2021 gets renamed to maybe even some react we'll hit update so our data in our database is now updated when we go back into our application refresh the page we are going to see that new information updated and the reason for this is because every time we refresh our page we are making a brand new call to mongodb to get that remote data loading it into our component and then re-rendering it to the screen so this is essentially how the get server side props method works all the code you write in it is going to execute every single time you refresh the page or you reload that route now reason you may not want to use git server side props is that every single time you reload a page or every single time a specific page is loaded with get server side props it's going to run that lambda function or it's going to you know make a call to your back and make a call to the database so if you have data that doesn't change often from the database making that call continuously just kind of seems wasteful so that's why uh next js also supports this get static props function which relies on static generation and if we look at the docs here it fetches data at build time so it's going to go so what this is going to do is it's going to make a call to the database when we build the application when we deploy it when it's first built it's going to get that data and render it once and make that information static so that we don't have to make a continuous call to the database back and forth uh every single time we reload the page and we can see how this works by going into our code and changing the get server-side props to get static props we'll hit save it's going to update our application so now if we go back into our app here we'll refresh make sure everything still works and if we go and change some of the data so i'm gonna just remove what i had previously we'll leave it as ngcom2021 hit update now when we reload the page we are actually uh seeing the chain and the reason for this is both the get server side props and get static props are gonna run every single time when you're in development mode so let's go ahead and restart our server but this time we're gonna run it in actual production mode so i'm gonna run npm run start rather than npm run dev and what this is gonna do is it's going to run the application as it were in production from the build directory rather than building it every single time we make a change so now if we go into our application and navigate to localhost 3000 events refresh the page it's going to load up really really quickly and we have ngcom 2021 mongodb world etc etc but if we go into our database and change some of the information so let's change ngcomp again to something else updated now if we go back into our application reload we are not going to see that change reflected so even though in our database we have ngcom2021 something else in our application because we are using get static props we are not getting the updated data so the data was pre-ren the data was generated and pre-rendered once the data is going to be rendered once and unless we specify how often we want that data to be refreshed it's going to remain static so even though we're making changes in our database we are not going to see those changes reflected in our next js application now to fix that all we need to do is go into our application here and after returning the props we're also going to pass in a second element and that element is going to be called unstable revalidate and then how often we want to update information in our application so let's say we want it updated let's just say we want to update it every second so what this is going to do is it's going to render readily available information that we have and then it's going to go ahead and refetch new information from the database so that on next reload you know every second here we're going to get the latest and most updated data so here i just put one second so that we can see the explanation so that we can see what happens but you know in a real world application you might set this to every minute or every 10 minutes if the data a if you're not expecting the data to be updated often so let's go ahead and rebuild our application and see what happens now so i'm going to stop this i'll run npm run build to build a new version of it and then we're going to start it in production again let's go back into our application now refresh and we're going to see the changes from earlier so we have something else else spelled wrong and then mongodb world 2022 instead of 2021 oops so now if we go back into our mongodb atlas cluster and change some of the data so let's fix longer or so let's fix ngcon 2021 remove the other information from it we'll hit update if we were to immediately refresh we're not going to see the changes but you know if we give it a couple seconds give next js time to go and refetch and revalidate that information then we're going to see the updated info so this kind of gives you the best of both worlds it gives you both the ability to prefetch data and have it load super super quickly when your application is loaded but also when data changes on the back end that you can get that latest data and have it displayed as well so we talked about get server-side props and get static props but there's one more method that we need to discuss and that is get static paths which is also related to static generation and what this method does is it's going to tell next js which dynamic routes to preload and pre-create pages for now to see how this works let's go into our code and open up this brackets id file now this component is very similar to our index component in that it's just going to render some information about an event and in this case rather than rendering all of the events it's just going to render one specific event and here what we are using is the get static paths method which is going to go into our mongodb database and get a list uh and get a list of all of the ids which we're using for our slugs or for our you know url parameters for our next js application and we are mapping all of those to a variable called paths and then returning those paths with a fallback set to true and then we are combining the get static paths method with the get static props to actually go ahead get that parameter id get our data and update it like we would and in this method we are also using the unstable revalidate set to one so that if we do make changes to our data it is successfully reflected now why do we need the get static paths method the reason that next.js provides this method is when we have dynamic pages that we want to generate we need to know what those urls are going to be and this get static paths method is going to take care of that for us now to see how this works i'm going to export my next.js application so that we can see what html files get generated when our application is built so if i were to run npm run export it's going to build and create essentially a static version of my site in a directory called out and we're going to be and we're going to be able to see the the pages that get static paths is automatically going to generate for us and this is going to fail because i am trying to combine server side props and static props so you know this application wouldn't run but i do want to see what gets generated so if we look at this out directory and look at the events we can see that for each event we have an html document that was created that is minified but we can see the content for it so for every document that we had in our mongodb database so we had six documents here we also have a statically generated page for it with all of the html all of the uh visual elements and this is what next js would do for us if we were to build and deploy this application to production on versal or a different platform so that is why we use this getstatic paths to figure out which static paths we need to generate and from there we let next.js handle everything else for us now we also have this fallback property that we need to return with the getstaticpass method tell next.js what to do in the event that a page was not pre-rendered at build time so if we set it to true what's going to happen is when we get a url so if we were to do events and pass in a object id for a new event for example that hasn't already been pre-rendered then nexjs is going to run the getstaticprops method on it and generate that data otherwise if we set it to false then we're just going to get an error saying that you know that page doesn't exist so let's see how this works so i have this fallback set to true and let me go ahead and rerun my application so what we're going to do is let's go into our mongodb atlas cluster and let's create a brand new event that doesn't already exist so if we go into our events page we see that we have one two three four five six different events now if we go in here let's create a new one so we will insert a document and we'll give it a name of next.js world insert that document and it should be here let's get its object id and try to navigate to that page what we're going to see is next.js world is successfully rendered because we had set that fallback property to true but if we were to set it to false let's say false and let me restart so i'll have to rebuild and restart let's run npm start so now we can go into our application into the events section and we see our seven different events if we go and create a new one and we'll call it react world let's copy its id now remember since we set the fallback to false we're going to get an error and the reason that we're getting this error is because we set that fallback property to false meaning that if we didn't already generate the page when we built the nexus application we're going to ignore all other pages and we're not going to try to do anything else now the last thing to keep in mind about these three methods within next.js is that all of these methods only run on the server so both get static props get server-side props and get static paths will never be sent to the client and the big benefit of this is that now you can run server side code that you would traditionally delegate to the api folder within xjs directly within the get static props and the git server side props methods so you can do all sorts of really unique things here so things like if we take a look at our speak.dev um project you know within here we are getting the user session server side getting their information getting stuff that we wouldn't want to expose to the client executing it within this getserversideprops method and then just passing it in as um as static props to our next.js component we can even bring in you know our mongodb client and run queries directly here exposing our connection string and not worry that it's going to be exposed to the client side and potentially exposed to the world and we can also validate that this code is never sent to the client side by checking this next.js code elimination project that tells us what is going to be bundled and sent to the client side so in this example here we have this getserversideprops method and this method is making a sql request so it's talking to a sql database getting its information getting its information and populating it to this project's prop but this server side prop all of this code is never sent to the client so i hope this video was helpful in explaining the data fetching capabilities of nexjs the static generation and server side rendering capabilities how they work and when you would want to use one over the other i hope you found the video useful and if you have any questions or comments please leave them below otherwise i will see you next time
Info
Channel: Ado Kukic
Views: 22,817
Rating: 4.9258399 out of 5
Keywords: NextJS, Next.js, getServerSideProps(), getServerSideProps, getStaticProps(), getStaticProps, NextJS Data Fetching, Data Fetching, NextJS Static Generation, NextJS Server Side Rendering, Server Side Rendering, Server-Side Rendering, SSR, Nextjs tutorial
Id: eWObYvG0-lI
Channel Id: undefined
Length: 19min 30sec (1170 seconds)
Published: Tue Jul 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.