Next.js Crash Course 2021

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's going on guys welcome to my next js crash course so i created one of these about three years ago or so when next was first released and a lot has changed since then and next has become super popular it's actually one of my favorite new or newish technologies i'm actually rebuilding my own website with it right now so we're gonna go through some slides talk a little bit about what it is what the benefits are and then we're going to jump in and i'm going to show you how we can create a project and work with next js now before we get started let's talk a little bit about what you should know before getting into next js you should know javascript of course you should also be comfortable with react and the fundamentals like creating components using jsx within components passing and dealing with props using state so if you're not familiar with this stuff then check out my react crash course i just redid it it should be the video right before this one but you definitely want to know the fundamentals of react first all right so let's talk about what next is because it this can confuse a lot of people because you have front-end frameworks you have back-end frameworks next is is sort of a combination of both so it's classified as a react front-end development web framework and it was created by a company called versal formerly known as zeit and it enables your react apps to have additional functionality such as server side rendering that's that's the main thing that it does is it allows you to render your react applications on the server and i'll explain more about that in the next slide it also allows you to generate static static websites so next is not something that's comparable to react itself or vue or angular or even a back back end framework like express so what it does is it builds on top of react to give you extra features that are incredibly handy especially when it comes to production and at this point if you're getting into building larger react applications you're building production apps next is definitely something that you're going to want to get into all right so i just want to talk a little bit about server side rendering and what that means so traditionally if you build an application using let's say create react app such as we did in the react crash course your entire application is rendered on the client side via javascript so the request gets redirected through a single html file then your javascript gets loaded and it displays your application in the browser so this allows you to have a really fast and interactive user interface when you compare it to let's say an older php type website where the server compiles the data and maybe uses a template engine or something like that and it delivers a formatted html page with all your content if it's done that way every time you want to navigate to a new route or you want to update your user interface you have to make a new request and reload the page now even though a client-side framework or an app built with a client-side framework is fast and dynamic there can be some shortcomings and one of the biggest is seo if you use create react app and you open up the source code in your browser you're not going to see any of your content you're not going to see the h1s or the h2s the paragraphs anything like that you'll see the main div that is later on replaced with your content via javascript now this is horrible for seo because search engine crawlers can't pick up your content and there's multiple ways of handling this but next js does this right out of the box because the first page load is rendered server-side rather than client-side not only does this increase performance in some situations but your content is also delivered directly so if you view the page source in the next js app you're going to see all that content and so are the search engine crawlers so you kind of get the best of both worlds you get the seo of a server side application but you still get that that you know that quick dynamic client-side routing and everything else that comes with a react app now performance and seo those are great reasons to use next js but there's other advantages as well so routing is a huge one with a traditional create react app we would have to define all of our routes with something like react router dom so in next you can actually create a file say about.js and just make it a react component either a class or function and you can put it in the pages folder and then go to whatever your domain or you know localhost slash about and that page will automatically be rendered so there's no need to use react router dom or anything like that it's sort of like with php if you want an about page you just create about.php you throw it on your server and you go to that route or that url in your browser and it shows up so that's another great thing about next and you can have dynamic parameters like let's say you want to go to slash posts slash one or two or whatever the id you can do that you just need to structure your files in a certain way and i'm going to get into that in a little bit now since your app is rendered server side you can also create api routes directly within the next file structure and that's just one option you can of course have an entire express backend or backend using some other language or framework you can also use like a headless cms if you want so there's lots of options for data but you do have the ability to create api routes within the next file structure which is really cool you also get out of the box typescript and sas typescript typescript is a superset of javascript that makes your code more robust you can simply change the file extensions to use typescript same with sas if you want to use sas you can change your css extension to dot scss another thing that you can do with next is export a static website similar to how you would use gatsby which is a static site generator static websites are really really fast and they can run without the you know needing a server and they can be hosted directly from a cdn of course you have certain caveats that you can't do with a static website we'll talk a little bit more about that later now as far as deployment you can host a next.js website or application on any service that can host a node.js app verso which is the company that created next has its own easy to use hosting service where you can just push to with your with a github repository or bitbucket wherever you store your application so that's an option you could use like heroku you could use any cloud host if you do export it as a static website it can be hosted absolutely anywhere including a cdn all right so that's going to do it for the slides now we're going to jump in we're going to use a tool called create next app to generate a new project and we'll go from there all right so this is the next js website nextjs.org and it might look a little different depending on when you're watching this video but if we go to the docs here the documentation is actually pretty straightforward it's not too much it's not overwhelming so if you have something that you don't understand in this crash course or something i don't mention you can check the documentation if we look at this getting started page you'll see under system requirements we do need at least no js 1013 installed so make sure you have that on your system and then to get set up there's actually a utility called create next app which is very similar to how create react app works just sets up a boilerplate application for us with a dev server and then you can also do a manual setup and just install everything separately but we're going to use this tool here so i'm going to open up my terminal and let's do npx create dash next dash app and then whatever you want to call this i'm going to call it next crash course and then i'm also just going to add dash dash use dash npm because i do have yarn and npm installed and i'm choosing to use npm and it's just going to set up a boilerplate app it's going to install react react dom and next all right so now we want to do is cd into whatever you called it i called it next js or next crash course and then i'm going to open up my text editor from here so i'm using vs code so we can just do code dot and now you can see all the files and folders on the side here now there's really not much which which i like it's really minimal so if we look at the package.json the only dependencies that are displayed here are next react and react dom and of course you know webpack and babel that stuff is being used but it's all behind the scenes it's we don't have to actually deal with it and then for scripts we have npm run dev is going to run nextdev which starts our development server on uh localhost 3000 we'll run that in a second we have npm run build that's going to build out our site for production and then start npm start will actually run the production build locally on your machine alright so pretty simple package.json now i'm going to open up my integrated terminal here and do npm run dev and you'll see server started on localhost 3000. we'll go ahead and click on that to open it and it's just going to be a welcome page welcome to next.js and then just some links that go to uh outside documentation so what i want to do now is just look at some of these folders so the public folder is basically your static folder anything that you put in here is going to be directly accessible from the browser for instance this favicon right here if i were to go to localhost 3000 slash favicon you'll see that it'll actually show here all right so be aware of that anything you put in there is going to is going to show in the browser so images you might want to put images in here maybe style sheets now there is a styles folder here there's there's so many different ways you can write css with next in fact there's there's a flag that you could use when you run create next app there's a style components flag if you want to use style components but i'm not going to get into that in this video so here the global css obviously this is global this is spread across the entire app and then it's recommended to i wouldn't say recommend it but it's it's common to have a specific css file for your different components or your different pages so this is called home.module.css and this this applies to the home page now in the pages folder here just ignore the api and the app.js for a second this index.js this is our home page and if we take a look at it it's nothing more than a react component called home all right you can see we're actually importing that reporting styles from that home.module.css so you could have an about page and maybe have an about css or whatever there's one kind of rule to this though you can't import global style sheets directly into components all right this global css is actually being imported here in app.js and i'll get to that in a second but just remember that you can import import global css and when you do import directly into a page or a component it has to be has to have this naming convention so home dot you can call this whatever you want but you have to have this dot module dot css then you can import it this could be anything you want you could say you know home styles or something like that you can call that whatever you want but just make sure you call this file dot module css now i'm just going to get rid of all the stuff for now uh actually we'll keep the head there i'll explain that in a minute but down here let's just have a div and get rid of everything inside of here because i think if we just if we keep too much it gets kind of complicated so i'm going to get rid of everything that's inside that div and let's just have an h1 and we'll say welcome to next now i'm going to save that and if i go over to my browser that's what we're going to see so it cleared up all that other stuff and i'm just gonna make this a little smaller now one of the best things about next is the routing system you don't have to actually bring in a third-party router you don't have to define your routes you simply put your pages inside of this pages folder and all your pages are react components so let's say i want an about page i'll create a new file here called about.js and here i'm just going to generate a react component let's just put in here we'll have an h1 and we'll say about so i'll save that and now if i go over to my browser and i just go to slash about that's going to load that page so it's as easy as that it's kind of like how you would do with php when you just upload something dot php to the server and then you can go to it in your you know in your browser and you can also do nested routes later on i'm going to show you how we can do something like articles slash 10 which would be a specific id for a specific article we just have to do kind of a we have to have a specific folder structure but we'll get into that later now i want to address this right here this import head from next slash head this is used if you want to have custom titles or meta tags maybe keywords descriptions things like that so down in the div here and it's the jsx it's just like if you're working with create react app you you have to have just a single parent element it doesn't have to be a div it could be you know just a fragment it could be whatever but you can't have something below here it has to be all within that parent element including the head here so let's say head and we'll say title and for the title i'm going to call this web dev news like that and let's say we wanted to have some keywords we could do meta tag with a name value and say keywords and then content let's say web development programming whatever and you could put a description and whatever you want in the head so if i save that you see now we have a title says web dev news but the other thing i want to show you is this is the source code you can open source as you normally would but i have this extension here i was a quick source viewer which just kind of cleans everything up for us i just want to show you that we can see in the source here you can see the keywords we just added and then down here you can see the h1 that's that's pretty much the only content we have on the page but any content you have all your headings all your paragraphs that's all going to display in the source code and it's accessible to search engine crawlers where if you if you create an application with create react app or any you know just any regular client-side single page application you're not going to see the content in the source code you're going to see the main div or the main element where your content is rendered once the javascript loads so again next.js is is very good for seo all right so let's let's actually close that up so if we wanted to have maybe a separate title for about so if we go to slash about right now doesn't look too good so we could you know take actually let's just take this and import that and then we could put head here and of course you could create a custom component we'll probably do that in a little bit where you don't have to keep repeating this you know bringing in head you just bring in your into your layout which we'll create in a few minutes you could have a custom component where you pass in the title and all that so if i go ahead and save now you can see that title is about now as far as layouts um let's do that so at this underscore app.js this is this wraps around all of your page components okay so it's just it's a function it takes in a component which is your your page component your page props and it just returns that but we could add a layout to this if we want we could wrap a layout around it that way we can have a header a footer a navigation whatever you want to show up on every page in that layout you could add to to the layout component and again this is where you want to import any global styles you don't have to do this module stuff here if you want just a global style sheet you could do that you just have to bring it in here not into a specific page or component so what i'm going to do is create a folder called components and this is for any components that are not pages okay anytime you you want a component where it's not going to have its own route its own url you're going to put it in here so let's create a new component and let's call it layout.js and the convention is to use lowercase for your pages and then uppercase for any other components that you're going to use so this layout is just going to be a react component and let's uh let's see we're just going to i'm actually going to use some of the classes in this home dot module now the the boilerplate just had all the styles in that one home page right they had the footer and all that stuff so i'm gonna actually rename this let's rename this to layout dot module dot css and what we'll do is bring that into this into our layout and there's so many different ways you can do this style components are really cool i plan on doing a crash course on that on those soon so let's import layout on port layout we want to import styles because we're importing styles from and that's going to be from let's see up one level styles slash layout.module.css then we can go down here and we can say classname and we want to set that to some curly braces and in here we want to say styles because that's what i brought it in as and then whatever class you want to use so container all right then i'm going to have a main tag in here and let's also add a class name here and i'm going to use styles let's do styles.main and of course you'd have your own styles but i'm just using kind of you know the boilerplates style sheet so we want this to actually wrap around if we look in our app.js again we want it to wrap around our page component so this is going to be passed in as a child okay so we want to bring in here as props we're going to bring in children and we want to display the content the page content here so here let's say children okay so we'll go ahead and save that and now in our app.js i like to have the style sheets at the bottom let's import our layout component so that's going to be from dot dot slash component slash layout and then what we'll do instead of returning this directly let's put some uh parentheses around that and then here we'll have our layout and then let's move this up into here oops we don't want that at the end all right so i'll go ahead and save that and now you can see some of the styles have changed because in our layout we're using the container class we're using the main class and i could put anything i want in here like right above the children here if i wanted to put h1 and just say hello and save that's going to show and if i go to slash about it's going to show there as well it's going to show on every page that that uses that layout all right i'm going to get rid of that though and then let's see back in our app.js so that looks good now as far as the styles go there's just a couple things i want to change here so the container instead of justify content center let's do flex start and then on main same thing flex start and we'll save that actually i'm also going to add font size we'll do 1.25 rem all right so what i want to do now is get into links and how do we get to the the about page and back to the home page and i want to create a separate nav component that we can use and create a nav bar at the top so it's going to have its own styles so first i'll go ahead and create a new file here and call it nav dot module module.css and i'm just going to paste the styles in it's not much so it's just going to be a simple you know regular just nav bar at the top here so we'll save that and then under components let's create a file called nav.js and we'll go ahead and create a component here we want to import these the style sheet that i just created and i'm going to import it as nav styles say from and then we want to go dot dot slash styles slash nav dot module dot css all right now down here let's change this div into a nav and i'm going to give it a class name and set that to nav styles dot nav and then let's put it have a ul here an li and then this is where i want to put my link now i don't want to use an a tag here what we do with next is we bring in something called link similar to what you would do with react router dom so we'll say import link from and that's going to be from next slash link okay and then down here we'll use that link which is going to take in an href and this is going to go to just the index page and we'll say home all right and then i'll just copy this down here we want this one to go to about so change that to about so let's save that now we want to bring this into our layout because we want these these links to be on every page so in our layout let's go ahead and import let's say import nav from and it's in the same folder so just nav and i actually want to put this above the container and stuff because i don't want it to be contained i want it to be up at the top and go all the way across so remember we can't we have to return just a single element so what i'll do is wrap this in just some empty angle brackets and then i'll put my nav here all right so we're still we still have just one single parent element so if i save that now you can see we have some navigation if i click on about it goes right to the about page home alright and obviously you could add more pages and more links if you want all right now i'm going to create a header that i want to display on every page all right so we can close up app.js so let's first create a style sheet here so create a new file called header.module.css and i'm just going to use some of the styles from the boilerplate let's see so we have container main footer i'm not going to do a footer so i'm just going to clear up these styles there's no need for them and then title any class of title and description is going to be in the header so we're just going to get these and cut those out save that close that up and then go into header and paste that in the only thing i want to add here is this color i want to add that to a span in the title as well so we're just going to add that okay so we can close that up let's now create a new component so in the components folder let's say header.js and we'll go ahead and create our react component and then let's import we'll call it header styles from and that's going to be in styles header dot module dot css now before i actually implement any of that and the styles from that file i want to show you we can actually use css in javascript with style jsx so i'm just going to put a span here let's say web dev and then news and let's say that i want to style this h1 within within my component so i could put a style tag here and just add jsx and then we could open up some curly braces and some backticks and then we could define a style like let's say class of title has a color of red and then up here we could add a class name and set that to title and of course we can't see anything because we haven't brought the header into our layout so let's go to layout let's go ahead and just copy this down and bring in header as header and i'm going to put this i want this to be within the main tag so basically right above the children that's where the page is output so here let's say header and there we go and you can see that it's red from this right here now this can get quite messy putting this right in your component you might want to do it if you have some kind of conditional conditional style so let's say we have a variable called x set it to 5 and then down here maybe we want to do like so since we're using backticks here we can use this syntax this money sign curly brace and we'll say if x is greater than 3 then let's make this red else let's make this blue so i'll save that you can see it's red if i change this to two now if i save this when we do it when we do this conditional styling we actually have to reload the page so now you can see that that is blue because of this condition so you might want to do something like that i'm going to get rid of this though and then for the the header styles that we brought in of course we want to replace this with header styles and we're going to use title here which make it a little bigger and then let's also add we'll add a paragraph and let's say keep up to date with the latest web dev news or whatever you want to put this needs the description class so class name and it's going to be header styles dot description all right cool so that's our header and it's going to be on every page okay so even if we create another page in here it that's going to automatically show because it's we brought it into our layout and that wraps all of our pages all right so we can close that up and we can actually just close all of these for now now before we move on to data fetching and all that i just want to talk a little bit about the the custom document that we can create so if we look at the source code here and you can see that we have we have obviously our html head tags body tags we don't have that anywhere in our file structure though by default also down here you'll see there's a bunch of scripts that are loaded including webpack and some other ones here so if you want access to like let's say we want to add a laying attribute to the html tag what you can do is create a custom document and i'm actually going to bring this this documentation page over and this will tell you more about it so a custom document is commonly used to augment your applications html and body tags and this if we want to override this we can actually create an underscore document.js file in our pages directory all right and this is actually rendered on the server so if we go down here let's see so custom attributes are allowed as props like lang caveats so it's only rendered on the server so you can't have like on clicks and stuff uh in this file all right and you would you probably don't really want to mess with this i just want to show you that it is possible so what we'll do is let's copy this because this is the the default document and then i'm gonna go to my pages folder here and create a new file called underscore document.js now if i just leave this blank let me just close that if i leave this blank and save it's not going to do anything because this is actually rendered on the server so i need to restart this so run npm run dev again and now when i reload i'm going to get an internal server error now to fix that i could either delete this and the default would be used or i can just paste in the default here and if i save that and reload my server now it should go back to normal all right and then what's happening here is we're bringing in the document class here and this this class is extending document this get initial props if you don't have to you probably don't have to deal with this you don't even need it so we could get rid of that if we want and the default will be used we don't even need the render if you're not going to edit anything here but basically we have the html tags the head the main which is this whole area our components our pages and the next script is any scripts that are being executed by next now if i want to add let's say lang here and we'll set that to en if i save that again i'm going to have to you know restart server here for that to take effect and if i reload and if i look at my page source you'll see now we have the lang attribute here so you can pass attributes in as props to html if you need to add something on the body or something like that so i just want to show you that in case you need to access this for any reason you probably don't want to in most cases if you want to add meta tags or anything like that you have the next slash head to work with with which i showed you you know back in uh index.js so you just import this and you can add whatever you want to the to the head all right so now we're going to get into some data fetching from within our pages we have some special functions that we can use to fetch data and then pass it into our page as props all right so we're going to go into our index.js our homepage and we can add these functions either above the component or below i'm going to choose to go below here and we want to export const and then the function now there's three separate methods that we can use to fetch data there's get static props which is going to allow us to fetch it build time there's get server side props where we would fetch the data on every request which is a little slower obviously and then we also have get static paths to dynamically generate paths based on the data we're fetching so we're going to use get static props here and i'm going to make this asynchronous because i am using a sync await here and i'm going to start off fetching data from a third party api called jsonplaceholder and then after that i'll show you how we can create our own api routes in the api folder all right so let's say const res and we want to await fetch and in here i'm going to go ahead and put in https jsonplaceholder.typeycode.com and i'm going to get posts so it's just this is just like a fake rest api i've used this in a lot of my videos and courses so it'll just get a bunch of posts for us i'm actually going to limit it though to six so we can add a parameter of underscore limit and set that to six okay then i'm going to create a variable here called articles and we want to await the response json so that'll give us the data and the way this get static props works is really cool actually we just return an object with props which is an object and then whatever data we want to pass in as props which in our case is going to be the articles we fetch so now if we go back up here to our function our component we can pass in here articles and we should be able to let's just do a console log here of articles and save and i'm just going to open up my console here you might have to reload since we're as we're using get static props and you can see i get six objects here with an id a title a body and a user id all right so what i want to do though is is list those out here so i'm going to get rid of that and what we can do is go down here let's get rid of the h1 and we'll go ahead and take those articles that we had fetched and let's call dot map and say for each article what do we want to show let's um for now we'll just do an h3 ultimately it's going to be a separate component but let's just do an h3 and we'll show the in here we'll show the article oops article.title so we'll save that and now you can see each title is rendering now i actually want to have some separate styles for the articles the grid and the card class in the layout is only going to be used for the article display so i'm going to grab grid card actually everything from grid down let's grab that and i don't think we're not using this code class anywhere so we could get rid of that as well and then let's create and styles a new file called article dot module dot css and just paste that in and save all right now if we want to use those we can import them now we could leave it like this but i think what i want to do is create a separate component called article list where we do this map and then have an article item component for each individual article all right so this is just react stuff you want to think of everything as a component so let's say article list dot js and we'll go ahead and oops i want to generate that and i'm also going to import let's say article styles from styles slash article.module.css and then i'm going to add to this a class name of article styles dot grid and what we can do is instead of doing the this map here let's cut that and we're going to be passing in articles as a prop here and then oops it should be plural and then here we'll just go ahead and paste that in all right and then in our index.js we'll bring in article list from let's say you want to go dot dot slash components slash article list and then just put that down here article list and we want to make sure we pass in a prop of articles and set that to the articles that were fetched okay we fetch them here and then we return them as props to this page and then we pass them into this component as props so if i save we're going to see the same thing the style is a little different because it's applying this grid we also want to apply the card style to each individual one so let's create another component here called article item.js and let's create a whoops let's create a react component here and we want to import i'm going to import the styles articles or yeah we'll call it what i call it here article style yeah so that's going to be from dot dot slash style slash article dot module dot css okay i'm also going to import link because we're going to have a link to each specific article so let's import link from next slash link and then this is going to take in a prop of a specific article so make sure that singular and we're going to return here a link href now we're going to talk a little bit more about nested links later but as far as where we want this to go it's going to go to article slash and then we want to use brackets here and id now what we want in that id is the id from this specific article so we can actually say as here and set this to some curly braces and backticks and say slash article slash and then the article dot id okay and then in here we're actually going to have an a tag it's not we're not going to use the href that's on the link but we'll have an a tag and i'm going to give this a class name and we want to use the card class so in here let's say articles styles dot card and then inside here let's do an h3 and we want to have the article dot title and i'm just gonna use i'm just gonna put an arrow here with the ampersand r rar semicolon and underneath that we'll have a paragraph and that will have the article body alright so if we save that and we go back to article list and bring that in go item from dot slash article item and then instead of an h3 we can get rid of that article item and then we just want to pass in as a prop the individual article all right so now we have each article showing here and it has that card class and it looks looks pretty decent i mean it's basically the same style as you know the default boilerplate if i click this it goes to article slash one right which is the id of that specific one if i click this one it goes to slash three but i just have a 404 page because this page doesn't exist so we can actually create nested routes like this so we can go to article slash and then whatever the id by going to pages i'm just going to collapse those and in pages i'm actually going to create a folder called article and then in that article folder i'm going to create another folder called brackets we want square brackets with id so whatever the parameter that we're going to use and then inside id the folder id i'm going to create an index.js and this is going to be our single article page so it's going to be a react component and instead of index though let's call it article and down here as well and let's just put in here this is an article okay and if i save that now you can see no more 404 it's showing this is an article if i go back and i click on just any of these the first one here it's going to show this same page now to get that id what we could do is we could use the next router so we could say import say use router from next slash router and then we could go let's go right above this return here and let's say const router equals use router and then we can this is now going to contain any parameters that are in the route so we can destructure those we could say let's take the id let's take that from router dot and it's router dot query and then i'm going to go down here instead of saying this is an article let's say this is article and then let's put in here id if i save that we get this is article one if i go to this one here this is article two i'm gonna keep this here and just comment it out so you know that you can do that and you could of course you know use fetch in inside of use effect or whatever but we're going to we're going to do this using the data fetching methods that next js provides to pages so i'm going to start off here with get server side props which will fetch the data at request at the time of request rather than get static props which will fetch it at build time so we're going to start off with this and then i'm going to show you how we can use something called get static paths to actually dynamically generate all of the paths with all of the data so let's first do const get server side props and set that to an async function now these get server-side props and get static props can get passed in a context and that will allow us to actually get the id of whatever is in the url so here let's do say consorez and set that to a weight fetch and inside here we'll put some backticks https jsonplaceholder. and then we want to go slash posts slash and then this is where we want the id so whatever the id is of the page which we can get from context dot params dot id all right so now we just want to let's create a variable called article it's going to be a single article and we want to await res.json that'll give us the article remember when we did get static get static props we returned the props we do the same thing here so say props which is an object and then inside here we're going to pass an article which then we can pass to our page up here article and now if i go over here and just say article dot id i should get the same thing so this is article two if i go to one this is article one i could get the title i'm actually gonna um yeah let's get rid of this div and just have some empty fragments here and then inside here let's have an h1 and i'm going to put the article title say article dot title save that should show us the title good and then let's go under the h1 we'll have paragraph and in this paragraph we'll do the article dot body okay there's the body i'm just going to put a line break in here and then i want a link to go back to to the home page or the article listing so up here let's import link from uh from next slash link and then down here let's say link href we want to set that just to go to slash and then we'll say go back so we save that now we have this link we can go back and we can get our articles now it's important to know that each time we're going to these pages is where this is when we're fetching the data right with get server side props so you can keep it like that if you want but you can also use a combination of get static props and get static paths to dynamically generate the paths with the data so i'm going to actually change this now to get static props and as soon as i do that i'm going to get an error that says get static paths is required for dynamic static site generated pages so we need to go down here and doing it this way is going to make it much faster because it's generated it's fetched at build time and you can use this in a static website so we're going to say export const get static paths and this is going to be async now we just want to make a request to get all of the posts so i'm going to just copy these two lines right here and instead of getting a specific id we don't want this context params we just want slash posts that's going to give us all of the posts which i'm calling articles when i say posts and articles are used interchangeably so let's call that articles and then what we need to return from this get static paths is a paths object which is going to look like this so it's going to be like params and then params is going to be an object with each id so let's say id1 and it's going to be it needs to be formatted as a string so then we'd have id 2 and so on so we essentially need to take the data that's returned which is an in an array of article or post objects and turn it into this and pass it into here so we can do that really with two lines of code so let's say const ids we can take each of the articles map through and let's say for each article we're going to return just the article dot id so that'll give us an array of the article ids now let's create another variable called paths and let's set that to the ids which we're going to map through and say for each id we want to return an object with params and in params we're going to have an object with the id which is going to equal the id but we want to format it as a string so two string will do that all right so doing this will actually give us what we need here and it will include every id of every post that's returned from this json placeholder so now we can just do that which will pass in this paths as that value all right we're also going to add here fallback is false which means if we go to something that you know doesn't exist in in the data it's going to return a 404 page all right so let's go ahead and save that and now what should have happened is it generated all the paths for us so if i go to home if i go to this one here we're seeing you know the the article with the id of two now notice we only have six here that we can click on right the last one here has the id of six however if i go to my url up here and i go to article 20 it's going to get me article 20 because what happened is it generated all the paths for all the articles slash posts whatever you want to call them alright which is really cool and we can actually export a static website with all of this data that came from that api in fact what i want to do now is show you how we can generate a static website using what we've created here alright so i'm just going to close up this stuff for now i'm going to get into the the api routes after but i just want to show you because while while we can we're using get static props um and we're using a third-party api that's you know it's it's always running we can generate a static site so i'm going to just go to my package.json and the way that we do this is with the command next export so when we run next build it builds for production you know we have this dot next folder which includes our server and stuff and when we deploy to you know verso or some other host we deploy everything uh however when we export it just goes into a folder called out and it is just a static website so i'm going to add another command here well actually you know we could do is we could just add it on to build so we'll say next build but we'll also do double ampersand and then next export so let's try that so i'm going to go ahead and stop this server right here and say npm run build and it's going to build for production like i said and it's also going to export a static website all right so it's built for production so we could upload all of this to versal or some any host that would you know handle node.js but we also have this out folder which is a completely static website now you want to run this on some kind of server if you would whether it's a cdn or whatever i'm actually going to use the serv package so if you don't have it you can just npm install dash g so you want to install this globally serve oops i forgot sudo all right so now we should be able to just say serve dash s and we want to serve the out folder which is our static site and i'm just going to add dash p so the port let's do 8 000. just make that a little bigger alright so it should be serving our static site so let's say https we want to go to eight thousand whoops not eighty thousand and there it is so this is a static site if i delete everything right now except for the out folder this is still going to run still going to work and you can see just how fast this is because it's all pre-fetched and we dynamically generated all of those paths so now let's stop this and let's go ahead and run npm run dev again because there's a couple more things that i want to get into okay so we'll close that up and this if you deploy to a server uh if we look at our get ignore that out folder is not going to be deployed okay so that's that's in your git ignore and we can actually just delete that now so i want to go into creating api routes so inside pages we have this api folder this is hello dot js and we have the a function that takes in a request and response and we can respond with a specific status code and we can respond with specific data so if you've ever used express or really any kind of you know building any kind of back end rest api then this is going to look really familiar so this hello js we can actually get rid of so let's delete that and then in api i'm going to create a folder called articles and let's create inside that a file called index.js so basically for every response or every function we're going to have a separate file and we're only going to have two we're going to have one to get all articles and one to get a single article now as far as where the data comes from that could be from from anywhere really and you can make database calls in here for instance i'm working on a website right now with next that uses prismo which allows you to interact with you know a postgres database or mysql database and you can use prisma inside here you can also use it inside your pages as well and i plan on doing a video on that but for now we're just going to use a javascript file with some data so i'm actually going to drag this over to the root of our application and i have the repository in the description for if you want to get this but you can see we just have an id a title i put an excerpt as well and then the body and these these titles in this this data is just copied from a blog so we have this data file so in our index.js here let's import this so we'll import articles from and we want to go actually we want to go up three levels into data and we want to go into actually it's just data data js and then let's go ahead and export a function here we want to export as default and we're going to call this just handler and this is going to take in a request response and all we're doing here is going to we're going to have our status so res.status of 200 which means everything is good and then dot json and we want to attach the articles all right that's it so we're just serving these articles from our api now if i save this and i go over to here when you create something inside this api folder it's going to be accessible automatically from api slash and then we called our resource articles so let's say api slash articles and there it is so we have this data that we can then fetch and do what we want with and again this just comes from a file but this could be from anywhere sqlite database whatever so that's to get all of the articles now i also want to be able to fetch a single article so to do that we're going to create another file inside of this api articles and we're going to call it id within brackets okay so brackets id dot js and i'm just going to copy what we have here because we're using the same data from that file and we want to be able to go to localhost 3000 or whatever slash api slash articles slash id and get the data for that specific id and the way that we can access that is with request.query.id or we can just destructure it since that's the only thing we're using up here so instead of that we can just say you know query and then from here we want id so we can do that and then we should just have access to the id variable so here let's get rid of that and then we need to filter out the specific article that we want by that id so we'll create a variable called filtered and let's set that to our articles so that's all of our articles but we want to filter out from that so say for each article we want to filter where the article dot id is equal to the id that's passed in from the request all right and then we'll just check for that so we'll say if let's say if filtered dot whoops filtered dot length so if that is greater than zero then let's send a res dot status of 200 and we'll pass jason we're going to pass in filtered now this is going to be an array but we just want the first element in it so just filtered zero that will give us a single article else so if something goes wrong then let's do a res.status and this is going to be a 404 because it's not found and then for jason we'll just pass message and we'll say actually let's use backticks here and we'll say article with the id of and then we could just pass in the id is not found okay so let's save that and let's try it out so we'll make a get request to api slash articles slash one and there it is now our as far as our data goes we have up to what four so if i try to fetch slash five i should get my message and this is a 404 response okay you can use postman or something with this if you want so now that we have this this tiny little api set up let's use this in our in our application here so i'm going to go to pages let's go to our index and this is where we made our request to jason placeholder so what i'm going to do i'm going to keep this here but i'm going to copy it and comment it out and then just paste this in and instead of making my request to jason placeholder let's get rid of that we want to make it to our api now if i if i try to do api slash and then articles like that and i saved that let's go back home so it's going to give me an error that says only absolute urls are supported so we can't even though it's on the same uh it's on localhost 3000 we still have to add our you know an absolute url so http localhost 3000 which is going to change if you deploy this right so what i would do is create a folder let's call it config and then we can create index.js in there and let's create a variable to see if we're in development so we'll set this to process dot env so our environment variables and we want to check the node environment and say if that is not equal to production okay and then here let's export const server and we'll set that we'll say put a ternary here and say if dev then return http localhost port 3000 else then let's make it i don't know https your website.com whatever whatever that's going to be so we'll save that and now we can go back to our index and we can bring that in so up at the top here let's say import server from that's going to be from dot dot slash config and then down here when we make our request we can just simply pass in here server all right so we'll save that and now you can see that it works these articles are actually being fetched through our api which ultimately is just coming from a javascript file but of course that could be from anywhere now if i click on one of these it's still going to show me the the content from jason placeholder because if we go into our pages article and then you know in our id file or folder the index.js we're still fetching from from jsonplaceholder so again i'm going to copy both of these and then just comment them out and let's go right above and paste these in and just fetch from our api now we do need the server from the config so i'll just copy i'll just type it out so up here let's say import server and that's going to be from and we want to go we're going to go up a couple levels here into go up one more into config and then down here instead of jsonplaceholder and instead of post because we called it articles so let's get rid of that and let's put in server and then we want to go slash i'm sorry slash api slash articles and then slash whatever the id in the url okay and then this down here can stay the same and then we want to do the same thing down here i'm just going to grab this and instead of this we'll have that okay and then we're going to get the articles we're going to map through the ids and create the paths and generate the path so let's go ahead and save this and now we're getting the actual data from our api click on that there we go all right cool so the last thing that i want to do is instead of on our all our pages right now if we want to have that's the wrong page if we want to have a title custom title meta tags and stuff like that then we have to import head on every page i don't want to have to do that i want to have a default meta component to put in our layout so in components let's create a new file we'll call it meta.js and that's going to be a react component and i'm going to import head here so import that from next slash head and i actually want this to take in some props so it'll take in a title let's say keywords and there's actually third-party packages you can use for stuff like this too next i think it's next dash seo is a good one so description and then i'm just actually going to paste in what i want to return here so it's going to be head and then inside head i'm going to have all this stuff so basically we have the viewport for responsiveness we have the keywords which are going to be the props that are passed in the description props character set utf-8 favicon and then the title and we can add default props too if we want so we can say metadot default props and let's set that to let's say title we'll set that to web dev news and then keywords we'll set that to web development programming and then a description we'll set that get the latest news in web dev all right now let's bring this into our layout so inside of our layout.js i'm going to copy that down and bring in meta and where we want to put this is just right at the top so right above nav we'll just say meta okay and then i'm going to get rid of in our pages here so let's go to our home page get rid of the head import get rid of this right here clean this up save that and then we'll go into where else about get rid of that head there and save that and our articles let's see we didn't do that we didn't do a head there all right so now if we go over here you can see we have web dev news is the title about also has web dev news so every page by default is going to have the default props that we use now if you want something different like in about if i wanted to have a different title then i would import meta here from say dot dot slash component slash meta and just put that right here and we could pass in a prop of title and set that to about so if i save that now we have about and even though it's on the layout it's not going to repeat twice like it's not going to give us two titles if we look at the description here so it just basically overwrites it so you can see title about all right so for the articles let's say we click here i actually want to have the article title as the page title so what we can do is same thing we'll copy let's go into pages article id index and let's bring in bring this in right here we'll bring in meta and in here let's say meta and pass in the title of article dot title okay so now these titles will be dynamic what's going on here can't resolve oh since we're it's actually three all right so now up here you can see the title of the page is the same title as the article all right and if you wanted to add maybe a description we could do description and we could set that to the article remember there's also an excerpt you could do that as well now if we check the description you can see the content here okay so good for seo and on the home page i think we are just outputting the body but if we wanted to go back to the home page actually not the home page this is in the article item instead of body we could do excerpt which is shorter like that okay so that's pretty much it that's uh all the fundamentals really i mean there might be some stuff that i missed again check the documentation and uh hopefully this at least let you know what next is and what it's good for and you can see the benefits of using it it's definitely um you know it's very popular these days and it makes production a lot easier so that's it guys i hope you enjoyed this crash course and i will see you next time
Info
Channel: Traversy Media
Views: 286,415
Rating: 4.9700508 out of 5
Keywords: nextjs, next.js, next js, react, react next.js, react.js, next js tutorial, ssr, ssg, server side react
Id: mTz0GXj8NN0
Channel Id: undefined
Length: 69min 45sec (4185 seconds)
Published: Tue Jan 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.