Beginner Next.js Tutorial - Coding A News App With Next.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Is there actually any benefit to using Next.js for small applications that don't deliver a lot of images or videos?

I've heard from a LOT of people that NextJS is the second coming of Jesus, but when I ask why they show features like dynamic bundle delivery which is great, but probably not worth it for my project.

Do I have that right or am I missing something?

๐Ÿ‘๏ธŽ︎ 2 ๐Ÿ‘ค๏ธŽ︎ u/rook218 ๐Ÿ“…๏ธŽ︎ Jan 06 2021 ๐Ÿ—ซ︎ replies

Do I have to know react to learn Next.js?

๐Ÿ‘๏ธŽ︎ 1 ๐Ÿ‘ค๏ธŽ︎ u/ChoicePurpose ๐Ÿ“…๏ธŽ︎ Jan 07 2021 ๐Ÿ—ซ︎ replies
Captions
hey everyone so this is the next.js tutorial that i promised now next.js is a react framework that allows us to do a lot of things such as server side rendering which i've got a video on linked below and other things too like static site generation and code splitting it takes a lot of that heavy lifting and handles it for us so that we don't have to worry about it now as i said it's a react framework so that means you need to be familiar with react in order to follow along with this tutorial now don't worry i've got tons of react videos ranging all the way from beginner to advanced i'll link some of those in the description as well now i'm about to demo what it is we're going to be building but first please go ahead and smash the like button for me subscribe if you haven't already i'm going to go ahead and get this ready all right everyone so this is what we're going to be building in this tutorial so as you can see we're on the home page right now and if i click the feed you can see that it takes me to a news feed with a bunch of different articles now if i were to scroll through this you can see the different articles each one has a title a description and an image if i were to click on the title it actually takes me to the the article itself so we're retrieving these from an api the api that we're using is called news api and we're going to sign up for that in just a moment don't worry it's entirely free you don't have to enter any credit card information whatsoever so don't worry about that so the second thing i want to show you about this news feed is that in the url here you probably can't see it so i'll read it out loud the url is slash feed slash one now that one represents what page we're on so if we scroll all the way to the bottom here you can see that this says number one which is also representative of the page we're currently on so i can click next page and it takes me to page two and the url updates to represent that as well and we have new articles we can go to page three etc we're gonna be able to go all the way to page five now this is interesting as well because i can come up to the url and type in four and it takes me to the fourth page here which is also represented correctly right here on the bottom now because this is server side rendering if i were to share this url on social media such as facebook or twitter it's going to represent the articles that are actually loaded from the api on the particular preview that we share i'll show you what i mean by that because we are going to be deploying this app in this tutorial so i'll show you actually what that looks like in other words if i were to share page four on facebook it's going to show the actual articles in the preview for page four or at least the first one and that is due to server-side rendering alright so let's look at the third tab eom that stands for employee of the month now i've put myself on here because i just didn't want to use anybody else's information but you can obviously put anybody you want here we're going to go through this in the tutorial but the reason why this page exists is because i again want to demonstrate the ability to server side render data we're actually going to be retrieving this information from a database in fact we're going to be using github for the database i'll show you all that in the tutorial don't worry but this is going to be really helpful to demonstrate how we can share a url and gather the information on the server side and have the actual facebook or twitter bot parse that and actually show it in the preview in a react application this would not work like that so in a next.js server side application this is going to work but in a standard single page application and react without server side rendering you would not get that preview and we'll we'll show that you know once we get there twitter this is just a url to my twitter you can put your own twitter of course but i just wanted to have four tabs i thought it looked nice so let's go ahead and dig into this tutorial alright so the first thing you're going to want to do is go to newsapi.org go ahead and sign up get your api key again you don't have to type in any sort of payment information go ahead and sign up get that api key and once you've got that we can actually begin integrating our news api into our app but you have to have this first so i figure let's go ahead and knock this out so if i click my username here you can actually see that i've got this all set up already and this is the api key here so once you sign up just go ahead and take your api key and keep this open in the browser maybe pin the tab you know just make sure you have access to this at all times and we'll use this a little bit later so go ahead and sign up and get that knocked out okay so i'm gonna assume you went ahead and signed up for the news api now i'm assuming also that you have npm and node.js installed since like i said before it's kind of a tutorial where i'm assuming you already have learned react and you're familiar with react that means you probably have npm and node.js installed if you don't go ahead and install that look it up knock that out and then come back but i'm going to assume you already have it so i'm going to show you what versions i have node v i'm on version 15. you don't have to be on version 15. you can have any version as long as it's node js 10.13 or later so use any version you want but i'm going to use 15 for this tutorial and if i do nvm-v you can also whoops my apologies npm-v you can see that i'm on version 7.0.2 as long as you have a late enough version of npm to use npx then this will work out for you just perfectly fine so in order to initialize our next js application i'm going to use npx and i'm going to say npx create next app and a space followed by the name of the app and that's going to be called next news when i press enter it's going to bring me through a setup process for this next.js application all right so on your end it might look a little bit different if it's your first time ever setting up a next js app it's probably going to ask you a few questions just go through the prompts in my case it didn't it just went ahead and created it so i'm going to cd into the directory and i'm going to open it up in my code editor and i'm going to be using vs code for this tutorial use any code editor you're familiar with and comfortable with so what i want to do is take a look through this directory and explain kind of everything that was generated for us okay so the first thing i want to start with obviously is the package json just to see what dependencies we have now we have next js and we have react and react dom so obviously since this is a react framework it's going to have to include react and react dom for us now we have three run commands so normally in a in a react application if you're using create react app you're probably going to run a command such as npm start in order to run the server on the dev side but in our case here we're going to be running a command called dev so we're going to say npm run dev whenever we want to run this project so speaking of that i'm going to go ahead and run npm run dev just to show you what pops up on the screen um on our boilerplate project that our create next app created for us you can see that it says started server on localhost 3000 so i'll run over to that it basically created a boilerplate project for us with some links and all that good stuff but we're gonna knock all that out we're gonna get rid of it and create our own stuff but uh yeah it's just kind of cool to see that this was created for us and you can see it says get started by editing pages slash index.js so let's hop into the project and have a look at that file that it's asking us to look at pages slash index.js so what is going on in here so this should look pretty familiar to you if you are used to react because this is literally just your standard react code there's nothing about this component that is anything different than what you would expect in a standard react application so that's good that means you can write your standard react code you don't really worry you don't really have to worry about learning much new stuff it's it's pretty simple next.js handles so much stuff for you if you already know react this is going to be super easy for you we're going to get rid of all of this and write our own code so i'm going to get rid of our return statement here and instead just return a simple fragment that says hello world and i'm going to save it and go back just to see that it did in fact update with hello world inside of the window now let's take a look at some of the other boilerplate code that's included in the project and talk about it we have this underscoreapp.js file now what this basically is is it's provided by nexjs you pretty much don't have to edit this but you can but it's sort of like a higher order component that and helps initialize the pages and it's kind of just used by the framework itself now you can edit this you can modify it in more advanced use cases for instance if you want to share state between pages but in this tutorial we're not going to edit this page whatsoever all right moving on to the api folder as you can see inside of the api folder we have a hello.js file let's take a look now if you're familiar at all with node.js and express.js you might realize that this kind of looks like an express js api function and it really kind of is this api folder allows us to write out of the box write serverless functions meaning that we can write api endpoint functions within our actual next.js project as if it were front end code and call them from our front end but if we deploy it to a server like for cell which i'm going to in this video you can call them as if they're back in functions and they'll actually run on a server that is handled by versel and on our dev environment it's actually handled to work right out of the box as well so if i were to run this via npm run dev these serverless functions would actually be running so that's super helpful we're not going to use these in this tutorial since this is a beginner next.js tutorial so i'm going to go ahead and delete this api folder but keep that in mind because that is insanely helpful in a lot of different use cases all right and then we have the public folder now if you look inside of this public folder you may say hey this is different than a react application in fact it is because in a react application standard react single page application what you would expect to see inside of here is an index.html file where we would be injecting our components into that html file and serving that however that does not exist in here and that's because instead of serving a single html file that we inject code into and serve to the client we're actually going to have different pages for every single page in a next js application so in the home page for example that you already saw we have the index.js file but if we wanted to create a new page for example the employee of the month page that you saw earlier on we would actually create an eom.js file which would represent that route eom.js would represent the eom page and don't worry we're going to be creating pages in this tutorial but for now i just want to take one more look at something we have a styles folder now there is a globals.css file where you can put all of your global css and that is going to be imported it's already imported inside of our underscore app.js file that is right here you can see the import is on the first line styles global css so this is what i was talking about shared state among pages we share the global css among all pages so it's imported in this app.js file and then we have component and page specific css that we're using css modules for and if you're familiar with create react app it's going to be pretty much the exact same thing you can create a class like this and then import this css module into your component or page and then reference it by saying styles.container and then that way it'll be containerized to that specific component and will not leak to other classes and styles will not just leak into other components and that sort of thing so css modules is available here now in the pattern of create react app they have all of their css modules in a single styles folder that's a little bit different than what i normally do i normally take the css and include them in the component or the the page i guess you could say in xjs the component folder so inside of here maybe i would have a different folder for every single page and that folder would contain the page itself and also a css module but since that's not the pattern here for the create next app generated code i'm going to follow the pattern that it created for us so i'm going to put all of my styles inside of this styles folder and import it from there so let's go ahead and begin actually creating some files now if you're not familiar with why you would use next.js over something like standard react please do take a look in the description at the video that is titled what is server side rendering because you're going to want to understand what the benefit of server side rendering is if you don't already otherwise you know you might you might as well just use react but if you understand the benefits behind using a technology such as next.js you'll highly benefit from it so go ahead and watch that if you haven't already and i'm going to go ahead and get started with some pages now if you remember in that header when i was demoing the app there was three pages and one link the link was to twitter so we don't have to create a page for that but there were two pages there was feed and there was eom which is employee of the month we're going to start with the eom page because that's going to be the easiest and then we'll move on to the feed afterwards now we're going to just be writing basically a standard react component so if you're familiar with creating react function components this is going to be very simple for you the only difference is we're going to have to make sure that it's a default export so that's really the only difference so let's say export const and i'll call this eom and set that equal to a function and below the function we have to export default eom so it has to be a default export for the pages for nextgs to be able to import these pages and serve them properly so let's start by going ahead and creating a div that we're going to return inside of our component and this div should have a class name we're going to give this component a class name of page container now we don't have this class yet we'll add it in just a moment and we're going to make it a global style and since it's a global style i don't have to use the styles dot syntax i can just use a standard string because it's not going to be locked down to a specific component so i can use this class name just like that now the first thing that we're going to want to put inside of here is another div which is going to be the container that is for the page itself and all the main content now at the top of this we can put an employee of the month header and save it and let's go back to our browser and actually go to the slash eon page click enter and now you can see that you see the eom employee of the month page what's super convenient about this is that we didn't have to add this anywhere next js actually automatically picked up on the fact that there was a new page that we added because we added it inside of the pages folder and it picked up on that and is serving that for us so it makes it super easy for us to just create new pages now this is pretty cool and all but we're going to want to actually have a employee of the month and since it's going to change every single month we want to get this from a database and we don't want to hard code this and push a update to the application every single time we change some data here so in order to do that we're going to use a the my json server api now i've already got an endpoint setup for you so you don't have to set up anything on your end unless you want to you can totally set up your own db.json file that's perfectly fine but in our case here if you just want to follow along just use the url that i'm going to be using in this tutorial now in order to do this since we want to make sure that all bots and all social media platforms and everything can render this data instead of just the raw skeleton we're going to want to make sure that we server side render this page so if we server side render this page then always what's going to happen is when it gets to the client it's going to be fully populated already so if any search bots such as google or social media platform bots were to parse this page the data would be inside of it and that is what we want here so how exactly can we do server side rendering well as i said next js makes it super easy for us to do server side rendering super easy so all we have to do is wherever we want to do any sort of server side rendering in any page that we may have we just go below the export function so below the component code itself right here on line 11 in my case and we're going to create and export a new function that we have to name get server side props so get server side props and this is a function that we're going to make asynchronous so put your async keyword there and it's going to take in a page context which is actually provided automatically by next.js and all of the code that we put inside of here we can run asynchronously on the server so we can go out to the database get some data all on the server and then pass it into our component as if it were props so that means we can inside of this server side props function go and grab the employee of the month and then pass it into this component as a prop which means that this component can now take a prop called employee that we're going to pass in from this function so all we really have to do is just fetch that data like we normally would on a client-side application so let's do that let's say const api response is equal to a weight so we'll use a weight here and then we'll just simply use the fetch api to call the url this is the url we want to call now this endpoint is literally just a endpoint to my github repo through a api service that is going to find a file that i created called db.json that contains an employee of the month object so here on my github this is the repository for this tutorial code i can scroll down and see that i've committed a file called db.json and i just have an object in here called employee of the month and the value is name port exe position software engineer and image to my profile image and then a small description this is super convenient because it allows me to have a mock database without actually having to set up a database you really don't have to worry about how all of this is happening i'm just explaining it so that you don't think this is magic i wanted you to understand it so that you can fully understand how we're doing this and you can change it on your own end as well and again you can commit your own db.json file and use your own data but if you just want to follow along please just use the url that i've got right here so as you can see we went ahead and fetched the api response but we have to convert it to json so let's call a uh let's create a const employee and set it equal to await api response dot json because the json function of what's returned from this fetch is asynchronous as well so calling this code basically takes the response parses out the body and turns it into json now all we have to do is return this object basically return it in such a way that this component can parse out that prop all we have to do is return an object with a property called props and then any props that we want to provide to this component we can put inside of this props object now all we want for this component is an employee object so let's go ahead and create an employee object and set that obviously equal to employee because we have it right here now in javascript you don't actually have to add this second colon and employees since it is the same name we can just create shorthand here just like this and save it and now we're returning an object with props inside of it and the employee object but i want to see what this looks like in the context of a actual component here on the browser so to do that i'm just going to console.log employee to see what this looks like then go to my browser go back to the application make sure that i'm on the eom page right click inspect go to the console and see that right now it's undefined now the thing is when you're working with next.js since there is a server server-side aspect for it sometimes when you're wanting to make updates you're gonna want to make sure that you refresh on the browser so if you click refresh now you can see that you're getting the data from the database you're actually getting that employee object from the server side render but also if you go to your console you can see that it's logging here as well so it's logging in the browser it's logging that employee object and it's also logging that employee object in the server so what that means is this is isomorphic javascript that we've written that is running on both the server and the client meaning that this is running once on the server it's getting served to the browser and then it's running again in the browser so just keep that in mind and if you're unfamiliar with what isomorphic javascript is i've got a video on that as well and i explain it in like three minutes so you may want to check that out if you need to but this is pretty cool because now we have this employee object that we're getting from a database let's go ahead and display the information that we want to display for a given employee of the month so pulling open my code i'm going to go underneath my h1 tag and create a new div and inside of here an h3 with the employee name now this is just standard jsx for react here so employee since we have that object employee.name and we can go underneath this and i'm going to do an h6 to have the position then the position of the employee so employee.position and again if you want to just take a look and see what pieces are available we're already logging it you can see description image name and position are what we can access so we need to get the description and image now let's go ahead and hop in here underneath the position let's add an image tag and set the source equal to employee.image and then finally underneath that we're going to go ahead and create a paragraph tag with the description for the employee save it and let's have a look so as you can see this information has been served to the browser as expected doesn't look very good we'll add the css in a second but i want to show you something interesting which is that if we right click inside of here go to view page source if i search inside of here for the image tag you can see that the image tag exists in the page source itself we actually have this it's right here you can see it it's in the page source what happens if we're not server side rendering this application what happens if we're doing all of this logic on the front end like we would be in the case of a standard react application well if we were rendering this all on the front end if we were to view the page source of this just like we did here what we would end up seeing instead is just a raw empty skeleton we wouldn't see any of that information inside of there that is what's making this server side rendering so powerful right now and that's just due to the fact that in a standard single page application you're loading in the skeleton from the server and then you're loading the javascript and then you're injecting everything on the browser instead of on the server alright let's go ahead and make this page look a little prettier so let's jump over to our code and go to our styles folder on the left and let's create a new style new file i apologize called eom i'm using all caps here dot module.css and inside of here is where we're going to put our css for this particular page so we have a we're going to create a main class we're going to use flex 1 because we're going to have that page container that we already added for the class name in the globals we're going to add that in the globals in a second but it's going to be flexbox so we're going to make the main flexbox as well so display flex align items should be center and we're going to also set the flex direction to column and let's set the margin top to 50 pixels we also want to have an employee of the month class and we're just going to set the text align to center here and finally let's go ahead and target the image inside of the employee of the month so we'll target the image here and we want to set the width to be hard-coded to 250 pixels and set the border radius to 100 percent to make it circular but we have to actually import this into our eom.js file in order to have access to these styles so let's import it like this it's going to be a default import so import styles from and we'll use a relative path here so dot dot forward slash styles forward slash eom.module.css and now that we have access to this styles object here that we're importing from our css module we can go ahead and begin adding our classes and we're going to want to add them inside just like we would with a normal react application so let's start with this div right here and give this a class name of styles.main i'm going to copy this to make it easier for the other ones inside of this div i'm going to give it a class name of styles.employee of the month let's save it and see what this looks like okay looks pretty good however let's go ahead and hop into our global css and add our page container class so on the left go over to your styles folder and open up globals.css go to the bottom and create a page container class that has a display of flex a height of 100 view height and a flex direction of column that looks like it's pretty much it for our eom page there's really nothing else we need to add here other than the fact that we're missing the toolbar but we're going to create a shared component for that that we can share among all of the pages we'll do that in just a moment but before we knock that out we might as well go ahead and set up our home page so let's go ahead and set up our homepage back in the code editor i'm going to close out all the tabs that i have open so far and go to my index.js file because that's where our home page lives and we're going to follow the same pattern by having a div in here with a class name of page container and that is going to be from the globals so we don't have to import it specifically and we don't have to use the css modules syntax we can just have a normal string so let's go ahead and create a div inside of here with a class name of styles.main now we don't have this main class yet we'll add in just a moment we're already importing the home.module.css so it'll be just as simple as going into that file and adding the class name inside of here we'll have a h1 tag that just says next.js news app and below this will have an h3 tag with a message in it that just says your one stop shop for the latest news articles so go ahead and save that and let's head over to our styles page which is inside of our styles folder and we have the home.modules right here and as you can see there's a bunch of stuff in here already that was generated by next js i'm just going to ctrl a and delete all of that so it's empty and i want to add a main class with a flex of 1 i want to set the display to flex i want to set align items to center so that it's vertically centered and i want to set the flex direction to column so actually align items becomes the opposite in this case and makes it centered horizontally but we do want it centered vertically as well so let's go ahead and set justify content to center as well but let's also target the h1 inside of the main class and set the margin top to negative 50 pixels and that is just due to the fact that the toolbar that we're going to be adding is going to have a margin of 50 pixels and we want it to look nice and centered so once we add this it's going to ignore that margin top of 50 pixels basically don't worry about that now just make sure that you add it and you'll see that aesthetic difference a little bit later so you can see that we have this nice and centered it looks pretty good but let's go ahead and add our toolbar so that we can go between the home page and the eom page now luckily for us this is going to be very much just plain react code in fact what we're about to write could almost not quite but almost be shared between a next.js and a react app the only difference is that we're going to be using the next js router instead of react router dom that we would normally use in a standard single page react application so outside of all of these folders in your root part of the folder go ahead and create a components directory and inside of here we're going to create a file called toolbar.js and this is where we're going to have our toolbar component so let's go ahead and start our toolbar component by exporting a function so export const toolbar and it's not going to take any props and since this is a standard react component and not a nexjs page notice the difference between the two this is a standard component we don't have to do a default export we can just export it like this but what do we need to do inside of here well the first thing we're going to have to do is think about the fact that we need to be able to route between pages so there is a router that's provided to us by next js and that is imported as use router from next slash router so go ahead and import that and then that's actually a hook that we can use and set to a variable just like this so i'm creating a variable here called router and setting it equal to use router and now we have access to the next js router and can use it pretty much just like a standard function so let's go ahead and return some jsx inside of here and we're going to follow the same kind of naming conventions for our class names and by that i mean we're going to use styles.main for the main div here but of course we do not have these the toolbar styles yet so jump over to your styles create new file toolbar dot styles dot oops toolbar.module.css and in here i'm just going to put the following css we're going to have a main class with a width of 100 a height of 50 pixels a display of flex and we're going to center that vertically by using justify content center then we're going to target divs inside of that and set the margin for each div inside of the main class to 25 pixels and set the cursor to be a pointer instead of the little arrow then on hover we want it to turn gray just so that there's some sort of effect that shows hey you can interact with this div and the divs are going to end up being the links so go ahead and add the css to your toolbar.module.css file and then you have to make sure that you import that file as well inside of your component just like you do in the other ones so go ahead and import styles default import from and then use your dot forward slash styles and then the name of the file and now that we have that we can have access to that main class so inside of here we're going to have several divs and each div is going to represent a link in that toolbar and if you remember there was four total the first one was the home and i'm gonna copy this and paste it four times the second one was the feed the third one was eom and then the last one was twitter for the first three we're going to use the next js router when you click on it and for the fourth one we're just going to literally redirect them to mine or your twitter page so we need to add an on click function to each of these each of these divs and what do we want to do when we click on say the home page well we want to router dot push and the route that we want to go to when we click home is just the forward slash root so if i click on that it's going to take me just to the standard base url and i will copy this and paste this into the feed div but instead of the forward slash route we were going to want to go to the feed route now what's different about the feed route which we have not created the page for yet is the fact that it's going to take another parameter and that is the page number so by default when we click on the feed url we want to go to the first page so i'm putting slash feed slash one now let's go to the eom paste that in obviously for this we're going to want to go to forward slash eom and finally for twitter if i paste this in instead of doing router.push let's just manipulate the actual url so i can say window let's access the window object window.location.href we can set that url to any hard-coded url you want in my case i'm gonna do https forward slash forward slash twitter.com port exe and now i've saved that and we're pretty much done with our toolbar component here which means since we're done with that component we can start putting it inside of our pages so go to your pages let's start with the home page and here inside of page container but outside of main so between these two divs right here let's throw in our toolbar and for me it went ahead and auto imported it but you'll want to make sure that it's imported here and it's a non-default export because we're not exporting it as a default and we are importing it from components toolbar so just make sure you're importing that and that you have it in between these two divs let's save it and go to the homepage and see what we have as you can see here we have a toolbar with the home page what happens if i click employee of the month if i click that it in fact takes me to my employee of the month page that we've created so we know it's working good the only problem is where's the toolbar well we need to add that toolbar to our eom page as well so hop into your eom page here in fact i'm just going to copy this import line and go into my eom page and just paste that here and also copy the toolbar here and paste it between the page container and the main just like the other component as well and as you can see now i can go between the home page and the employee of the month page using the toolbar let's test out our twitter url so if i click that it takes me to my twitter so we have all of the toolbar items working other than the feed and that's going to be the most important part since this is a news app let's go ahead and work on the feed component now if i click it you can see what it says is 404 this page could not be found so it handles 404s for us automatically which is great um you can see that the url is slash feed slash one let's go ahead and talk about this for a second because the other components we created pages like this we created a page called eom and we're not expecting any sort of extra parameters such as slash one or slash anything else slash january slash february we're not expecting any sort of extra parameters so we've created a file that represents the actual name of the path so how could we create a page that could be different depending on a parameter for example feed slash one is page one and will contain different data than say feed slash two how can we do that next js again makes it super simple for us to do that so instead of creating a simple file we're going to create a folder and it's going to be called feed now feed is going to represent that particular piece of the url since it's slash feed slash 1 or slash feed slash 2 etc inside of the feed folder we're going to create a new file which is going to take two square brackets and then we can put in a name of a variable here in my case i'm going to call it slug you don't have to call it slug you could call it like page id or something like that but i'm going to call it slug.js and what's going to happen is we're going to be able to create our page our feed page inside of this just like we would with any other of the pages but it's going to be a dynamic route now so to build this component i'm going to start by just knocking out some boilerplate and then we're going to work on some server side rendering stuff so export const feed is equal to a function and then inside of here i'm going to return some very basic jsx which is just a react fragment that says hello world and make sure that you export it as a default so export default feed now i'm going to save this and i want to see what happens when i go to my page here let's refresh and we can see that nothing's happening that's because we have to have a parameter here if we wanted to have a say like a feed and then also be able to have feed 1 and feed 2 feed 3 then we would have to be able we would have to go into our pages and then outside of the feed folder create a feed.js but in our case we only want to go to the feed route if we have this second page parameter here so if i go to feed slash one now it loads hello world here and it does not care which page we're on so now i'm on feed 14. it doesn't care it has no idea it does not care about that second parameter that's because what we're gonna do is we're gonna take and parse out that second parameter get the data from the api and then populate it inside of our component here on the server side which means that this is going to end up taking a couple of props it's going to take a page number prop and a articles prop and we're gonna grab the page number from the url and we're going to grab articles based on that page number from the news api on the server side and then pass it into this component as props we are going to need to create our get server side props function so export const get server side props and it's going to be an asynchronous function again it takes the page context and it is a function that we are going to use to gather some data asynchronously and render on the server so the first thing we want to do is get the page number which is actually in the url that the browser's requesting so we can grab that from our page context that we're getting pat oops that we're passing in that we're getting passed in automatically from next.js so let's create a variable called page number and set it equal to pagecontext.query.slug now query is going to be an object that contains this slug property and the reason why it's called slug is because i named this file slug in square brackets if i would have named this say pid for page id then this would be pid instead so if you named this something other than slug make sure that you reference that correctly here if we don't have a page number or if page number is for some reason less than one in other words we don't want any negative page numbers or a zero page number or if page number is greater than five then we don't really want to send any props because we don't want to get anything from the api if it's page zero or if it's anything greater than page five because that's just how the application is going to be working so in that case let's return an object to our component with props let's just set articles to an empty array and let's set page number to 1. now if that's not the case if we have a the correct page number that we would expect let's go ahead and call our api now this is what i'm doing here i'm creating an api response variable that i'm setting equal to whatever this fetch returns what are we fetching well in my case here i have the url that is the following ap newsapi.org v2 top headlines now for country i'm in the united states so i'm using country equals u.s and if you are outside of the country you can go to their docs and see what countries they support otherwise you can just use us for the tutorial i'm adding the and symbol here and the page size i want to be five so that means five articles per page and the page number is this page query parameter here i'm dynamically setting to the page number that we are getting from the url so if this is page four then this value here will be four as well and that's all inside of the url now notice something is i've got this headers and we're setting authorization that's because we need to have our private key our api key inside of our header now since this is being run on the server we don't have to actually worry about our key being exposed to the browser in other words we don't really have to worry about people seeing our key but we don't want to commit this to source code because if we commit it to source code then anybody can if this is public can see that so what i'm doing here is i'm setting the authorization header to bearer and then i'm pulling the value from an environment variable so let's go ahead and add this environment variable so that we don't expose this to the public so to do this first you're going to want to run over to your git ignore file and you're going to see a list of dot n files here at the top i'm just going to add one more that's just literally dot end and that's it that way it ignores our environment variable file and does not commit that to our github which we're going to add it to later so go ahead and add that and then inside of your root directory create a new file and it's going to be called dot env and inside of here create a new env var called next public news key and you're going to want to set it equal to your api key so go to your project go to your api key copy that and paste it in after this equals sign right here so it'll be like so it'll look something like that so just go ahead and do that i'm not going to show you mine because i don't want to expose it but just go ahead and do that really quick once you've saved that and you've closed that file when we run our process when we run our dev server it's going to load that dot end file automatically and now this will be that api key so this will end up being that api key so this request should work for you but in order to get it to work we have to restart our server so go to wherever you're running your server close it out i used control c to close it out and run npm run dev again just to get this thing running now it's running on my local host and that is great it should now be loading the end var so i'm going to refresh because i just want to make sure that the server side code is refreshed as well just something that i like to do so we have this api response and we have the the correct header and we have the correct url and we're fetching it but we need to convert it to json so const api json is equal to a weight and we're going to take the api response and call the json function on it so now we have the api json but what does this object look like well in order to demonstrate that we can simply log console.log api json so i'm going to log this and pull open my my terminal here and get ready to look at this but i have to quickly go to here i'm going to go to page let's say page 3 because we can't be above page five because we have that if statement that blocks us from doing that go to page three and click enter you're gonna get an error that's fine just go over to your terminal window and see what it logs it logs a an array of objects and this object each object is an article and this array of articles belongs to a property called articles on the object api json so since we're logging api json we can grab all of the articles by saying api json.articles but i'm going to use destructuring assignment to grab it instead of doing it that way which just looks like this const articles is equal to api json i just think that looks a little bit cleaner sorry there should not be parentheses there um const articles equals api json so now we're pulling the articles out we have that array of articles we want to go ahead and give that to our component because it's expecting those as props so let's do that let's return an object and this object has a property called props and we want to pass two things to it if you remember page number and articles we already have both of these we have page number here at the top and we have articles so it's very simple we just go ahead and return both of those inside of this object so articles and we want to return page number but let's actually make it an actual number because right now when we pull it from the url it's actually a string but let's go ahead and convert that to a number so that our component inside of the browser has access to the raw number instead so number.parseint page number go ahead and save that and let's refresh and now we don't get that error let's go up to our component and log articles and let's also log page numbers so i'm logging both article and page number inside of my feed component which means i should be able to see these logs inside of the component and in fact i do page number is three which it is in my case and if i go and open up this articles array i can see the data for all of the articles for page 3 from my news api so what that basically means for us is we can go ahead and begin displaying all of this data on our news feed so let's go to our component here and begin writing our actual feed component so inside of the return i'm going to open it up and follow the standard pattern of a div with a class name of styles.main and inside of here i want to loop through our articles i want to map through our articles and map each article to a div with some stuff inside of it so to do that i'm going to open up my curly braces this is just standard react stuff articles.map and i'm going to map each one of these to a div so we should take both of the we'll say article and we need to access the index because each time we map through a list of something and map it to a div it needs to have a key and we're going to use the index for that key so we're going to map each one to a div and like i said it's going to take a key which i'm going to set equal to index so that react is happy and i'm going to give it a class name of styles.post and we have not added these classes yet so don't worry just add it now and we'll get to that in a moment inside of this div we want to add a couple of things we want to add an h1 and this h1 is going to contain the title so article dot title i just want to see what this looks like now so i'm going to save it and go into here and we can see i'm already getting an error and that's because the i'm not importing the styles yet so let's go ahead and actually just create our styles file we'll populate the file a little bit later but go ahead and go to your styles folder and create a feed.module.css and i'm just going to close it out and import it so that i don't get that error in it so import styles from feed.module.css save and i refresh and i don't get that error anymore and i see all of the five different titles for the articles for page three if i were to change this url to page one you'll see that we get different articles so we know that the page number is working so we want to make sure that we have other information than just the titles obviously so let's hop below this h1 where we're putting the title and throw a paragraph tag in here and some parentheses i'm sorry curly braces and throw in article dot description and then below that we'll go ahead and add the image but we only want to add the image if the image exists and there might be cases where there will be an article but there's no image for it so what i'm doing here is i'm just checking to make sure that the image exists and if it does i'm loading an image tag with the source equal to article.url to image save this let's have a look at what we have here so now we have the the information we would expect to see but it's kind of large i don't really want to see it this large i want it to look better so that's just as simple as going in and adding the styles so let's quickly add our styles so heading over to the styles folder we just created that feed.module.css i'm pasting in my styles i'm going to go over it really quick so we have the main pretty standard with the rest of the components then we have the post and each post is going to have a width of 500 pixels a margin top and a margin bottom of 25 pixels and a border bottom of one pixels solid black we target the image inside of the post and set the width to 100 we target the h1 inside of the post set the font size to 16 the cursor to pointer and the text align to center save this and let's see what it looks like this looks way better this looks totally presentable now this isn't you know a really good news app because i can't go to the actual news article i'm clicking this and nothing's happening that's because we have to add an on click event for the actual title because when we click on the title we want to go to the news article itself so going back to my feed component where the title is i'm going to add this on click function which just takes uh though it sets the window.location.href equal to the article.url so it takes that article url and sets it to the on click target and when i refresh inside of here you can see that dow drops over 500 points that's not good but if i click it it takes us to the actual news article itself and now we're on the fox business website so this is really starting to look like a working fully working application here but i need to be able to go from page to page i don't want the users to have to click manually inside of the url and set the page to two i want there to be a paginator at the bottom so that they can click on the different pages and go to the page that they want to be on so we're going to create a paginator at the bottom of this feed component so going back into the component if you highlight inside of main we're gonna go below main but in order to go below main we're gonna have to have a container for this so i'm gonna cut this and add a div with a class name of page container and paste the main back inside of here and below main is where our paginator is going to go so i'm going to throw in another div class name equal to styles.paginator okay so we have the paginator div what do we want to add in here if you remember there was three things inside of there there was previous page that we could click on to go to the previous page in the middle was the page number itself and then on the right was next page so we could click it and go to the next page so in that order if we go ahead and start entering this in we can start with the previous page so throw in a div here the class name this is going to be dynamic because if we're on page one we don't want to allow the user to click on that and go to page zero we want to gray it out and disallow anybody from clicking on it so if page is one so if page number is one we're going to use a ternary operator here pages one then we're going to want to add the styles dot disabled class otherwise we're going to say styles.active so we're doing styles to active if the page number's not one otherwise we're doing styles.disabled if it is but we also need to have an on click event here and in this on click event we want to make sure that we do not run if the page number is one so if the page number is greater than one then we can run some logic otherwise we're just not going to run anything at all but what is it we want to run whenever we click on previous page it's pretty simple we need to import the router so let's go ahead and import the router and we've already imported the router in the toolbar so you should be somewhat familiar with what that looks like i'm importing it from next router and then at the top of my component i need to set the router variable just like this const router equals use router so i have the router now and what i want to do is say router.push i want to go to slash feed and then whatever the page number is minus one so i'm using this string interpolation here to do that these are the backticks here and where i want to inject my javascript is right here page number minus one so if we're on page three if i click this we're gonna go to slash feed slash page three minus one which is two all right so we have the cl on click and we have the class name for it we just wanna add the text so in between the opening and closing tag here i'm just going to say previous page click save and let's go to the component and see what this looks like here at the bottom so at the bottom here i have this um this previous page thing right here now i'm on page two what what do you think is going to happen when i click on it i clicked on it it brought us to page one now what happens if i click on it again nothing happens and that's great because we're on page one and we don't want to go to the previous page if we're on page one because there is no previous page however there's a couple of things that's going on here that i don't like one is the styles looks terrible so we can go ahead and knock out the styles in a second and the other thing is when i clicked on previous page it didn't scroll back up to the top and that didn't feel right so next.js is aware of this it's not really a problem they don't consider it a bug they want us to handle it ourselves which is fine we can do but they are actually going to add this as the automatic behavior in the future so if you're watching this in the future it might not do that but if you are watching this and it is doing that the way to fix that is to go to where we are routing and route.push actually is a promise if i hover over push you can see that it returns a promise of type boolean so that means we can call then on it and so i'll call dot then and whenever we finish routing i'm going to set window.scroll2 to zero zero and when i save that if i go back to say page2 scroll down click on previous page it goes to the previous page and then sets the scroll back to the top which is the behavior that i think seems more intuitive so let's start by making this paginator look a little bit better before we add the other pieces so jump into your feed.module.css file go to the bottom and let's start adding a couple of classes we have a paginator class actually we're only going to yeah no we'll add a few classes so we'll start with a width and i want to set the width of the actual paginator to be a hundred percent then the display i'm gonna do flex and finally we're gonna justify the content to center so that everything is centered inside of it horizontally now let's target each individual div inside of the paginator set the margin for each of these to 25 pixels okay and then now we're gonna have the active and disabled class so inside of paginator we're gonna target the disabled class first and set the cursor to be set the cursor to be not allowed and we want to set the color to be this like grayed out color so that it's more obvious that you can't click it so i'm doing rgb179179179 now in the case of active we're just going to override that by putting it above it so make sure it's above disabled because css goes down in order we want to set the active case to cursor pointer and we will just set the we will not set the color it'll just be the default color if it's active so going back down here as you can see since i'm on page one it's grayed out and the the uh the cursor is that not allowed thing it's very obvious that i'm not allowed to click this super cool so back to the feed i'm going to add the page number in the middle so that's the second piece to this paginator so going over here underneath this div but still inside of the paginator we'll add another div which i will go ahead and put a number sign and then we want it in javascript put in page number so let's save that see what that looks like now we have both the previous page and the page number if i go to page two you can see that now previous page is enabled and active and instead of page number one we see number two the final piece to this was the next page button which is going to be very very similar to the previous page button so i'm actually going to copy the previous page div here go underneath the page number div paste this in instead of previous i want this to say next and the check here is going to be slightly different instead of saying greater than 1 we want to check if it's equal to five because if the page number is equal to five instead of checking for greater than one we wanna check for greater than five actually we wanna check for less than five so if the page number is less than five then we can go to the next page because if it's not less than five we don't wanna go past page five in our application here so instead of also doing page number minus one since we're going to the next page we're gonna say page number plus one and then just make sure that we're scrolling to the top here now in the case of the class name we want to instead of checking if it's equal to one check if it's equal to five so let's go ahead save that and go into our go into our feed and see what we end up with so i'm on page two if i scroll down you can see we have previous page the page number is two and we have next page so i click it and now i'm on page three that works page four that works page five now i'm on page five if i scroll all the way down you can see that next page is disabled i cannot click that this says page five that's good if i go to page one you can see that the previous page button is disabled and i can't click that so all that's left on this page is to be able to add the toolbar so let's add the toolbar really quick which is very simple we can copy the import from the eom page and paste it in at the top here of our feed page and then of course inside of page container and outside of main go ahead and add in your toolbar tag save and i'm going to click refresh okay this is saying okay and the reason why this is breaking is because we're actually one more directory in because we're inside of a feed folder so we need to add one more set of dots here in our import now if i save it and refresh it's working good i've got my toolbar here at the top so i can go to the home page i can go to the feed and i can see employee of the month so this app is pretty much done now you have a fully working next.js application however what i want to do is show you how to deploy this to versel and then show you some of the benefits of our server-side rendering when trying to post to certain social media websites so with that being said let's go ahead and push our project to github so what you'll want to do is go to wherever you have your project in your terminal or you know command line interface and make sure you're in the directory and run git add now it should have already created a git repository for you when you ran create next app so it it already has a repository set up for you so all you have to do is just make sure you commit your your your code so just run you know git add dot just your standard get stuff this isn't a get tutorial so i'm going to assume you know how to use git so i i did get add and now i've staged all my changes and now i'm just going to commit my changes really quick so git commit dash m and i'm just going to say init because this is the initial commit now i'm going to check get branch just to see what branch i'm on and i'm on the main branch and what i'm going to do is i'm going to push this out to github so what you're going to want to do is go to github create a new repository call it you know whatever you want i would make sure that it's called next news just so that it matches push this out there so if you need to do a basic uh tutorial on git if you want to move forward that's perfectly fine but i would expect you probably at least know how to use github go ahead and push this repository out to github and then resume this tutorial once you've done that so i've got my github repository right here i would expect you to now have a github repository with all of your code inside of it just like this so with that being said what we're going to do now is go to versailles so go to vercell.com and you'll go you'll go ahead and sign up now go ahead and sign up again it's completely free no payment information required go ahead and sign up for versailles and go to your dashboard now on your dashboard click new project and what we will do is we're going to import a git repository so i'm going to go ahead and click on this link right here it says missing git repository adjust github app permissions and in my case i need to explicitly go in and give access to vercell to access this repository so i'm scrolling down here and i'm going to um i'm going to add this next news repository so i'm searching for next and you can see port exe slash next news is there and i'm going to click save so now vercell has access to that repository and since it now has access i can click this import button next to next news and you can notice that it detected the fact that it was an xjs application versel is the company that oversees next js so this is the this is the platform you would likely want to publish your next js app to in the first place so click import i'm going to click on the personal account here because i don't have a pro account so just click on your personal account i'm going to let it stay next news you can name this whatever you want but now we have to go down to our build and output settings my apologies the environment variables because we created an environment variable inside of our app to host our api key you're going to want to add these environment variables here now so go into where you added your environment variables in that dot n file if i go over to the left here you can see inside of this dot end file go ahead and click that and go back here to this environment variables screen zoom in a little bit for you and you're going to want to add in that next public news key as the name and then the value is going to be your actual api key so go ahead and add in that value really quick and then click add and then we'll move forward now that i've added that you can see that we have this environment variable called next public news key with an encrypted value cool so all you have to do now is go ahead and click deploy this is going to run a deploy process that will take a few minutes to probably run and i'm going to go ahead and resume once it's completed on my end so as soon as that completed i was presented with this screen right here and it says congratulations it's been deployed now on the left here i can actually see a screenshot of the actual website which makes me feel like it's promising that it's actually working because that is what it looks like so if i go and hover over this visit button i can click it and now you can see i am on the actual website this is where your app now lives on the internet now it's called next newsflax.vsl.app it'll probably be called something different on your end obviously a different url but let's just make sure this whole thing works so if i click feed i in fact see a news feed i can go to the next page i can go to employee of the month and i see the employee of the month data right here and twitter brings me to my twitter page so this is a fully deployed nexjs app working very very easy to get this thing running up and in production now this is where we get to show you some really cool stuff now this can be considered part of some extracurricular activities and stuff i really just wanted to show you that this works but if you want to see this work in action for yourself you can do it you know for yourself but i added some extra code that i'm going to show you right now that i did not show in the earlier part of the tutorial you can add it yourself but again i just really wanted to show you how this works so i'm going to go to my pages let's go to the employee of the month page i imported head from next slash head which is just included automatically as part of the main next js library and i'm using this head tag now what is this doing well it allows me to add headers into my html document just like you would be able to add headers in a static html document but it allows us to add headers that are actually injected into the the actual source document itself which means that these will be present whenever a google bot or a social media bot parses this webpage and i'm setting the standard meta tags that we would expect to add in a in a good seo app or an app that we would want to have a preview for if we're sharing the link on say twitter or facebook or something like that so i'm adding these tags in and then populating it dynamically with the data that i've gotten from this employee object which means that we're having dynamic data set into the header on the server and what this ends up allowing us to do is be able to customize what this information is going to look like when we share it on something like facebook for example so i've gone over to this this facebook for developers debugger tool at developers.facebook.comtools.debug and i've pasted in my link and ran the scraper and you can see that when i've done that now it knows what to show when i share this link on facebook so this is what the link preview would look like it says employee of the month and this is for the um specifically for the employee of the month route it shows employee of the month and then there's a small description underneath it that says this month's employee of the month is port exe and it shows the image if i didn't have all of that information in there if this wasn't server side rendered if this was a standard react app this would look empty it would try to pull some information but it would only have that skeleton available for it it wouldn't have all this data from the database it wouldn't really know what to show so this is really powerful all right well i certainly hope you enjoyed this tutorial you built a next.js application and you deployed this thing to a production environment with server-side rendering great job now if you did enjoy this video please like this video subscribe so you don't miss any future tutorials and i'll see you all in the next video [Music] [Music]
Info
Channel: PortEXE
Views: 23,810
Rating: undefined out of 5
Keywords: nextjs tutorial, beginner nextjs tutorial, server side rendering, nextjs, next.js, server side rendering nextjs, server side rendering tutorial, how to server side rendering, react nextjs, vercel, vercel tutorial, react 2021, nextjs 2021, nextjs 10
Id: xtItzwYG6oQ
Channel Id: undefined
Length: 62min 47sec (3767 seconds)
Published: Wed Jan 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.