Advanced Next.js Course | Learn Next.js in 2021

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Thanks for sharing this!

👍︎︎ 2 👤︎︎ u/aercticana 📅︎︎ Jan 18 2021 🗫︎ replies

Thank you so much!

👍︎︎ 1 👤︎︎ u/pottas 📅︎︎ Jan 18 2021 🗫︎ replies

Thanks! Some great content in here!

👍︎︎ 1 👤︎︎ u/nickbeukema 📅︎︎ Jan 18 2021 🗫︎ replies

Is this "advanced" or just an intro?

👍︎︎ 1 👤︎︎ u/Jamesfromvenice 📅︎︎ Jan 22 2021 🗫︎ replies
Captions
hey youtube welcome to the full next chase advanced course this course is packed with tons of value but if you like this video and if you want to continue learning nexus and similar technologies you can go ahead and follow the learning path on codedam.com and specifically this next year's mastery path and it's going to contain tons of more courses information hands-on practice and all of that is accessible once you upgrade to a code damn lead membership you can find a 10 discount link in the description only and only for this video so go ahead and sign up for the first month you're going to get 10 off and you're going to be having access to all the content inside next year's mastery which is gonna be fundamental for you in order to become a proper nexus developer it's not only just gonna create have video courses including this one but content even beyond that so i'm super excited to have you on board on this course on youtube but if you feel like you know you can spend some money you can um you know buy the course and have access to the lead membership of the platform that would mean a world to me so yeah that's pretty much it and let's just go ahead and start with the video course hey everyone welcome to another next chairs course in this course we'll be learning about advanced sides of next year's so if you're somebody who's new to nexus and do not even know what next year says this is probably not the course for you you can start with next years by going to learning paths and opening the next year's mastery which is going to give you access to a complete breakdown of how to begin with next shares and spoiler alert next is almost like react right so if you have been a react developer you're good enough to start with next chase but again this is not a starting course this is more of an advanced side of course i'll be skipping over a lot of details which we have already covered in the basic courses so do not expect those details in this one so let's get started without wasting any time from the next video onwards we're going to be picking cherry picking some difficult to understand topics and i'm going to be breaking them into simpler concepts so that we are able to understand how that thing exactly works so that will be all for this video i'm gonna see you in the next one pretty soon hey everyone welcome back and in this video let us just go ahead and take a look at environment variables and how to manage them in next year's application i have already created an app so i'm assuming you already have you're already inside an application so this is a very simple application hello world you know the server is not running let's just do a yarn dev here real quick and if you go to localhost 3000 you're going to see the website would work just fine now what do you want to do first of all is you want to understand what environment variables are exactly what happens now is that let's just take example of development and production right so if you are developing a particular application you would have a lot of software's either local or on an infrastructure which is not supposed to receive very high volume of traffic right we also call this sometimes a staging so development work happens either on either locally or on staging production work happens well on production servers which are you know configured for high loads and high availability and all that stuff so often times when you are iterating and developing and doing all that stuff not only is it a better choice to have a separate server but sometimes it is actually impossible to have production server access because if they are guarded by firewalls or you know if uh your main application is part of a network which does not permit outside connection so there could be a lot of reason so the way you manage those external resources is that you keep your application stateless about them that means your application code this code right here does not matter if it's react or you know no chase logic or anything which we'll see in a couple of videos on server side props and all that stuff your application code should not be aware about where it is running right that is the goal and how do you make sure of that you abstract away the important details the important information of production or development in certain environment variables which come from the environment itself just like the name suggests that if you're running in a development environment that means if you're running on a local system or a less powered machine you're testing stuff the variables a few variables are filled in by the environment not by your code similarly for production so for production you might have a a large i don't know like um 16 gb ram 1tb ssd mongodb i don't know if that is even a good configuration for a database like that but you can have an instance for that right on a development you might want because you know you know that traffic won't be a lot so you might have a 1gb 50 gb ssd right so how do you convey the connection points that is the connection url because you know if you're connecting with you're gonna probably do something like mongoose.connect if you're using mongoose and then mongodb localhost and then the port number and then basically the you know the name of the database so how do you do this well you can see right here this is a stateful path that means your code should be aware it's it's not technically stateful i'm actually using the wrong word it's more about that you have hard-coded uh your um you know environment sort of here so what you eventually want to do is you want this to bring you want to bring this from environment that is process.env and then you probably want something like mongodb connection url right you want to do something like this so how do you make sure that when you ship this code on production when you ship this correctly this environment these environment variables are automatically populated so you do that with the help of next chase internal support for local and production and development environment and let's discuss all of that so i'm going to go ahead and explain that to you by starting off by creating.env.localfile and the moment i do that you're going to see if you're using vs code you're going to see this gets dim and the reason it gets dim is because this is automatically added by next shares in the git ignore file and there's a good reason for this now i'm going to come to the reason later on let's just discuss about what this thing does first of all so let's just say i'm gonna add a secret variable right and i'm gonna just put this value as coded.com right so secret variable is now a code that holds a codenam.com variable value but how do you access it well i actually just showed you how you access it so what you can do is uh right here you can say console.log or maybe let's not do here because that might confuse you so let's just do export function get so site props and you can just return this has empty and you can just console.log process.env dot secret variable right now if you go ahead and take a look at this actually if i go ahead and uh you know refresh this you're gonna see that you actually get undefined now the reason for that is because nexus does not use javascript to include these files these variables they are done before next year starts the server which is a good thing why because well you know you remove the overhead of including the environment file with javascript so that means if any time you are making a change to your environment file you gotta restart your server right so that's that's one thing so once you do that and refresh it then you're going to see now you get coded.com as the console.log now remember that uh you know we are obviously working right now dot env.localfile but just a couple of quick points if you try to do it here a few observations you will be able to make so let's just do uh you know env value just to separate that and i'm going to do process dot env dot secret variable right now you know that because you're using next js this guy this function is going to run both on server and on client right why because servo means server side rendering and client well means hydration right because next react would try to hydrate the tree in order to have you know see if we have any event listeners or anything unless you of course opt out of that manually but right now it's enabled so what next.js does is that technically on the browser you have nothing as such process but nexus would polyfill that for you and this would be available as an object however this value right here will not be accessible on browser of course of course you don't want this value to be accessible on browser right because we will be storing stuff like db host um you know production dot mongodb your whole string and then db username and dv password so you of course don't want that to be available on the browser but anyway let's just confirm if that is the case or not so i'm going to go ahead and refresh it here you can see the env value which we get in the node terminal remember this is the node terminal this is the back end it's not the front end is correct coded.com but if you go to the console here on the front end i think i have some search term you can see on the front end it's undefined right if i refresh it again you're going to see back and gives us the correct value the front end does not so there's obviously just like i said a good explanation why nextgs will not pre-fill or you know just supply the variables to front-end now with that being done of course there could be times when you want uh variables to be available on front end as well right because let's say you have a client side api and you want to have a token or a secret key for example a common use case i can think of is recaptcha so the way you do that is you do include next underscore public right and i think that's it and then whatever you want to name this this is a mandatory syntax this is hard coded into next year's framework so you have to include that there is no uh you know magical reason for this you just need this because the framework says you to do that and i can say my first browser variable and you can give you know underscores there i just did not feel like that and you can say some value yeah i'm bad at not only just naming variables but putting values inside them as well so once you do that now you can do a process dot env dot this thing and of course just like i said you got to restart the terminal because well nexus needs that and once you refresh this you're going to see once the page compiles you get some value on server obviously because that's environment variable but you also get some value on client right so that means whenever you prefix your variable with next underscore public underscore your variable gets exposed on the browser front so this is how you work with what this is basically the introduction to environment variables how you work with them in xjs and how the dot e and v dot local file populates variables inside your node process and inside the browser in the next video we're going to be seeing a little bit more on the management of the environment variables and some conventions you should keep in mind so that is all for this one i'm going to see you in the next video hey everyone welcome back and in this video let's just go ahead and take a look at a little bit of management of this dot env.local file and a couple of other files which are interesting to us now what nextgs does is that it comes hard coded with three files dot env.local.env.development development and dot env dot production now talking about the convention what you can think of is that these two files these files as templates right now these files can consist of you know non-secret variables as well if you want because you can ship them on um you know version control that is git or github whatever you want to you know do uh it's not like you you can ship obviously you can ship.env.local as well but the convention the good practice is to ship these two files and to have only the secrets which you know not are not really secrets but only the variables which you can afford to make public or to make accessible to anyone for example some stripe client key right which you can access both on server and on client on the browser so that could be inside this particular file this file however what next chase recommends is that you should have specific values and should be available only on your local systems for example database passwords right for example stripe secret key so stuff like this this should not be on the version control system this should not be uh you know in the pro in the deployment pipeline this file should be individually present on the production servers as well as you can create it for yourself on your local systems because you know when you're working on local just like i said in the last video your staging passwords would be different from production service passwords right and your uh for example stripe mode stripe would all obviously be operating into the development mode so you're gonna have a little bit of different values so that's better to have different value depending on different environments however let's talk about how next year streets if you have all these three files present so i'm going to go ahead and create dot env.development and dot env oops dot env.production here and i'm going to create a new variable i'm going to say uh specificity check zero right dot local gets zero development gets one and production gets two so if i go ahead and right now just to uh check here and say specificity check what do you think would console log zero one or two let's see so you know obviously you can make sense of that you won't really get the production console log because well we are not running it on production so it's it's more of a choice between zero and one so if i refresh this page you're gonna see that we get a value of zero and why is that because whatever variables whatever values which are present in the dot env.local file will override anything else right with they will override the development or production depending on uh where you're running it so of course if it does not has this dot env.local does not has this and if you refresh restart the server again and refresh the page you're gonna see that you get one which is the fallback value right so you get the one but the moment you add it something else it will fall back or it will consider env.local as the primary store how you gonna ship this env.local uh to production you won't right you won't ship this file to production you would either just code it once and leave it right there on the production server and if you want to update it you have to manually update it or a better way for production is to you know probably not have.env.local at all and maybe use something like uh for example if you're running aws lambdas you know that you know you can specify environment variables directly from the interface so maybe you can use something like that it depends on how you want to execute it on production but on development well next yes it's going to do that job for you so what about this.erv.production and development as you might have guessed by now next is detects what you are running where you are running next yes right now if it is development it's going to include this file if it is production it's going to include this file and how does it detect that well it uses process.env.node enb variable which you can see in the source code of nexus as well i just open the node modules folder and just search for enb and you can you know i won't really want you to make sense of this but this is pretty much a place where i believe it's trying to figure out the name of the file right so what you can see is that it tries to play with the process.dnv.dnv and it might have set this variable value depending on how you are building the project as well right if you're building it in a production mode it's going to be set as production if you're building a development it might not be set at all so on and so forth you don't really have to worry about that but yeah that's pretty much it on uh how you're gonna set some environments and get started with that stuff in next year's so that will be all for this video i'm gonna see you in the next one hey everyone welcome back and in this video let's just go ahead and take a look at and take a good look at actually what gets server side props is now we have uh you know you might have some experience some knowledge of get server side props what it does and all that stuff but let's just get into depth of what exactly this does so first things first what exactly this server side prop function is well you see that the architecture of next shares is as follows next year says that hey whatever page you want visible you want to live on your domain for example if you own codedam.com then if you want to have something which the user can see something meaningful which the user can see on abc and one two three or maybe like let's just keep it abcdef for now what you gotta do is you gotta go to pages directory and create a file called abcdef.jsx or js right now what happens when a person visits this url is that internally if this is not a static build assuming there's a next year server running if this is not a static build nextgs is going to check if this file if this file has a function called get server side props now this might be a little bit misleading because it does not check that for every single request when you're building your application it's going to mark certain routes which uh have this function right so when you're building an xjs app what's going to do it's going to see that okay abcdef uses this get server side props therefore i'm going to be a little bit more careful whenever somebody visits this and how is next year's careful is that whenever somebody visits this it's gonna not immediately serve the html page the user it's gonna first of all run this function whatever it this function includes whatever instructions this includes and then it's going to render the page right i hope that's clear if you do not have this for example if we have a route let's say this was dynamic right and this is static if we have this route which has no get server side props so what's going to happen when you build the application nexus is gonna mark as uh you know server side rendering it's gonna mark the dynamic page a server side rendering and it's gonna just say mark as uh static completely static completely static or you know i'm assuming that there is no get static props as well here so mark is completely static there we go so whenever somebody was static nexus is gonna immediately throw uh the already generated page or already generated html file uh which your server already has right but with dynamic it's gonna say wait a minute we also have a javascript some node.js logic to run so let's run that first and then let's just go ahead and run the whole generation of the page again in javascript right so you are running a lot of lot of javascript when you are using it server side prompts on every single request so what happens exactly is that you always on a particular request on a dynamic request you always run javascript before actually rendering the page it's very similar to how you know back in the days php would work so if you have a php file what you're gonna do is that you know you're gonna have some php syntax like this and then maybe you can uh connect to db fetch rows and then display data right that's how you're gonna do in php similarly if you want to do a similar behavior in next shares what you can do is you can um you know right here inside kits oversight props you can have this function as async first of all and then you can say something like uh db is await connect to db right rows db dot fetch rows whatever this is just dummy data and then finally you know send the rows to your react component as props then you receive the props right here and you know you destructure the rows from props and then maybe you map it and render it and all that stuff when that happens next js is gonna execute this particular javascript piece piece of javascript and it's gonna create static html out of it and then it's gonna send it to the client right on every single request this function is executing on every single one of them so that's that's that's powerful but that is also resource extensive right because now you are running node.js on every single request if you are uh you know coming from express background or express shares you know that what we do usually is express uh we usually throw express.static and then you know just serve static files directly and then maybe if you have a api route for example app.app.post you know something like that then your application then these static files might be able to make a request to this particular api but next chase follows a little bit of different convention if you try to go with server-side rendering and that is okay exactly the point of server-side rendering right that you render the output dynamically so you can get true server side rendering with next shares truly in what that means by using get server side props but again just like i said server side ring ring comes with its expense that it is in fact server side rendering and nexus is gonna run this for every single request um unless of course you introduce your own caching layer in between for a cdn or something but that's that's a different story right but that's how it happens now the internals of how this happens we're going to be pretty much like seeing that from topic to topic that is what happens what is in the context variable but if you go ahead and just just try to explore this i think we won't really have a auto complete without typescript but uh let's just go ahead and console.log it right so that we can just see some common properties and if you go ahead and refresh this page now and we get serializing props returned yeah anyway so you can see we have a bunch of data with us but interestingly you're gonna see right here the first thing which we have is a request right so so yeah i want to dive a little bit deeper into these variables and the values so let's just keep it in the next video i'm going to see you in the next one really quick in which we're going to discuss about a little bit about these past values all right guys welcome back and in this video let's just take a look at what all information we are getting at with the get server side props and mind you that gets oversight props is like the most powerful function in nexjs therefore you can pretty much expect this function right here to give you access to literally everything you can imagine on a single request right so let's see the first thing which we saw is the request variable which again is is a sort of an incoming this is an internal nodejs http dot incoming message uh interface but you're going to see that this pretty much follows a little bit of express shares pattern we're going to see that so everything you need about a request that is the url path for example the raw url the raw http information you know we can also see you have the socket right here if you want to send a rips response you have all the headers which the request url made um you have raw header information which is also something and you have the method you have the url you have the you know connection upgrade all that stuff information as well so you have basically everything right here in terms of raw node.js request processing right so if if you try to do something like i don't know context dot request dot uh not really request we're gonna do it with response so let's just see that first of all so response is again something similar to um what you're gonna see inside of a typical nodejs server so if you are if you have ever ever created a http nodejs server you're gonna see the first two things you get is a request and response parameter right for every single request so if you try to do context.response.end like this and that's it if you try to go ahead and do that and if i refresh this page right here you're going to see we pretty much get a very not so good request ending right so if i refresh this well we get 200 as the status code but that's pretty much it we don't really see anything else so you could pretty much just set a context.rest.status as 403 as well refresh this and nope this should be status code not status refresh this and you can see you get a 403 right here you can set it to 418 that is i'm a teapot i like the status code but yeah you're going to get that so you can see this pretty much is an actual server right this this you get a server level control inside this function it does not matter that you're running a react app below it right if you try to do uh you know nasty stuff here you can do as much as you want so you can even have a you know context context.rest.json i don't think if they have a json let's just go ahead and try send json dot stringify something cool right if you do something like this refresh uh let's send is not a function so maybe like i don't know write not really send rest not right refresh and we have a fail request probably not i just restarted the server and now you can see it looks pretty much like a json response from the home page of a next.js application right so that might seem weird if you're if you had the nexus is just you can just send react as the stuff that's not true right you can use gets oversight props to truly um get a server-like experience from nextgs as well so anyway that is something some sort of fun which you can do with next year's parameters let's just keep going there's a lot of more stuff here which next year's brings us so idly if you think about it request and response are the only two things which you need right so if you console log the request you're gonna see you pretty much will have every single information every single thing you need so let me just go ahead and refresh this again real quick and you can see that you will have cookies you know you're gonna have request.url right here you're going to have method you're going to have headers you're going to have everything but working with this in a raw fashion is a little bit uh cumbersome so what nextgs does is that it gives you access to a bunch of other things as well so the first thing let's just keep it to the you know this this sort of way as well because i will not be able to miss any property in this one so we have already covered request right and response which are the two biggest sort of objects on the screen right now but we also have a bunch of other things right so we have uh this query which is an interesting thing this query would be automatically populated by nexjs depending on how you are splitting your route right so let's see what let's let's take a look at what this means so i'm going to go ahead and rename this index.js to dynamic.js right and this dynamic word could literally be anything this could be code damn as well so i'm going to go ahead and take a look at code down just make sure this you know that this could be anything so once we do that what next chase is going to do is it's going to serve this particular file on every single route one level down right so i can have page one and that is served by this code down.js and the reason i hope you know is because this is a dynamic route because it's in square brackets again hard coded deep into next year's uh that is something you have to follow for now page two also lands on the same thing page three also lands on the same thing but interestingly if you take a look in the console you're gonna see the query parameter now gets populated with code down now you don't necessarily need this because you can extract you can technically extract this information from the url from the request.url parameter as well because if you go to url you're going to see this as page 3 then you can have your own regular expressions and run against that to extract the parameters but why do that when next chase is doing the heavy lifting for you so you can literally just go ahead and do context dot query dot ur context.query.codam and you are pretty sure that this value will be present 100 why because you know that the file name is the square brackets codename and next js is not going to run this function for anything which does not match this routing pattern i mean that's that's exactly the point of routing pattern right so you need no validation nothing here you know that this will work and this will have a valid value if it does not that's a nexus bug not yours so anyway you have something like this and this is actually interesting because if you go ahead and give it a query parameter you're going to have query is 2 right here now if you take a look you're going to see right here that we probably okay yeah we are losing the context that's why so refresh and you can see that query right here interestingly gets all the stuff that is your dynamic segments of the url as well as the actual query parameters which are the question marks uh which are the syntax followed by question marks right however the patterns right here only get the dynamic patterns right so here's an interesting finding which i did the other day and that is if i try to change this to code damp the query parameter the actual query parameter because you know this question mark and stuff is actually called query parameter then it would actually just drop the query parameter at all from the query right so this is likely a bug i don't know maybe i'll report it but now if you technically want to extract this to you have to do it yourself right because the request.query.codamp favors the actual [Music] sort of dynamic route before the actual thing which it should have supported but nonetheless this works fine for anything else if i have an underscore right here you're gonna see we get a code down underscore at 2. so that's fine but uh yeah that's something to consider so yeah we have a bunch of different attributes as well params just like i discussed would only contain the dynamic segments of the url not the query parameters uh we also have preview i think we do not have a preview here which is an interesting property or maybe we do i don't know preview do we have a preview no but we're gonna discuss about preview and preview data and all that stuff later on as well but that's pretty much it that should get you started that should get you familiar with get server side props at least one use case which i can tell you which i also use at codedam.com at the moment is that you can generate sitemap dot xml like this right so you can generate site maps on nexus websites and return the response as xml you might think this is a static file but this is actually a dynamic next.js file which is server side vendor because obviously if you're not using server side rendering you can pretty much just return html react response nothing else you can only return json and all that stuff without being inside api folder you can only return that if you're using its oversight props so anyway that's pretty much it for this video let's just keep it to this one that is all and i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just go ahead and take a look at what return value of gets oversight prop looks like so you're gonna see that we return an object with just props which is a little bit boring but you can make it a little bit more exciting by having a bunch of more properties so not only props you can return a different form of value as well so what you can do is that instead of returning props if you return something like redirect and then you can specify a bunch of mode parameters this route will actually perform a redirect on that particular url which is pretty cool and which is something you can do with a custom next.config.js file as well which you're going to see later on again but this is one way to go about so you can say destination destination as i don't know like google.com and then you also have to specify permanent now this permanent is an option which is basically uh responsible for setting http status code on your browser right your browser considers 301 that is 301 as a status code which means that will permanently map inside its memory that this url always maps to this one and 302 is a temporary direct so if you set this to false it's going to perform a redirect with 302 right so let's just take a look at that first of all so i'm going to go ahead and refresh this page right here and okay so we are not actually returning the value at all so let's just go ahead and refresh it now and we have a little bit of problem i think the server died anyway let's refresh it again and now you can see that we are redirected to google but if you take a look it actually it actually responds with 307 not 302 but anyway you get the idea right but if i switch this to true it's going to perform a 301 redirect so if i go back and refresh this you're going to see now well again i'm actually wrong it's three zero eight and three zero seven back in the day when i remember uh it was three zero one and three zero two this at this i mean these are also like these are also these will be also valid redirect permanent and temporary but there might be a little subtle difference in the rest guidelines depending on i guess the method and the data which you want to continue but anyway the point being that this means permanent redirect and that means now chrome your browser whatever unless you clear cache or anything it's not gonna uh look up for the server right before it actually hits that free direct so you can see it saves me from this cache now so even if i go ahead and do a false right here and if i go ahead and visit this url you're going to see that it redirects me with 308 only and even if i go ahead and remove this all together with the props which should now technically render content and if i visit this you're gonna see i'm basically screwed right unless i clear my disk cache so that's what permanent and temporary data means and that is why you should be careful about them because by mistake if you set a permanent redirect to a url and people started visiting them and if you wanted to make a change you would not be able to go ahead and refresh cash on their browsers right so you might end up in a bad state so anyway that's one way another way is another thing you can do is have a not found right here so once you have now not found as true this is basically something similar similar can speak similar to 404 as the status code and the typical standard nexus template so if you go ahead and actually of course i can't really use that url unless i clear my cache which i'm not interested right now so i can just go to page one so now you can see we get a 404 and a 404 status quo so these are like you know you just you can just go ahead and let's say fetch from db and you see that hey that does not exist then if no record exist then return not found right something like this otherwise you're going to continue and return props right here and just like us just like it you know demonstrate with props you can have something as a prof value return you can and whatever you return as a prop you can grab that right here so you can say create prop start something right so if i have create this you're gonna have create one next app as the title of the page right so if i refresh this you're gonna see record is not found yep sure so if i refresh this you're gonna see we have the title as create one next app right so yeah that's in a nutshell how uh nextgs get server side props method would overall work like just like i said it could be an async function you can be pretty much fetching data from different apis feel free to use fetch here you know you can do data is equal to await fetch something like google.com and remember because you're running this inside node context this is perfectly fine you're not gonna have any same origin policy stuff so you can have then t t dot text and then you can say slice 0 to 200 for example and now you can just go ahead and say pre and then props dot google first 200 yes something like that you know i don't know i just completely made that up very quickly and i can say yeah that's pretty much it right so i hope that works let's see right so it kind of works right because you can see right here you get the first 200 characters from the google home page which looks fine so anyway that's that's how you're gonna make it work and yeah that's pretty much it for this video i'm gonna see you in the next one really soon so what is going on everybody welcome back and in this video we're gonna be taking a look at get static props in next year's big big thing um you know a lot of power for next shares comes from this method so i'm gonna get rid of get server side props we might probably see how we can use both of them together later on but for now let's just focus on this bad boy called get static props super powerful method and super powerful concept as well which you know borrows a lot of learnings from the architecture of client cdn and then servo right so you know if you are in the in the loop there's also this neat framework called remix although it's paid it's premium but remix does not follow this approach remix follows the traditional approach next js has come with a sort of a new thing i won't really say it's new gatsby also uses it but it's a model where essentially what you're trying to do is a you are trying to build pages on build time right so what does this mean first of all this means that you as an application let's say you have uh 20 static routes right and 35 dynamic routes dynamic means that you have those in this form now these 20 static routes are simple right you just have to create an html and json payload out of them and just store them on the disk whenever somebody visits and just bam them with that static files that's simple this dynamic section what happens is that assuming that these are not server side rendering what you can do is you can build them ahead of time for example let's say you're running a ecommerce store simple e-commerce store with 35 products right and you have a database which contains these 35 products so instead of using get server side props and just fetching the product again and again for every single visitor in individually what you can do is that just build them ahead of time sure it might take you you know a couple of minutes on your continuous integration deployment servers but it will be worth it why because you have now uh complete static builds of those dynamic sort of pages as well that's one way another way which is interesting and where the power of get static prop lies incrementally or you know lazily build pages right or rather build a website which consists of pages here what happens is that out of your 35 dynamic routes ahead of time ahead of time that is on the build time you build zero pages right and whenever somebody visits let's say your store slash let's say this dynamic route is actually store slash id right so whenever somebody visits store slash one you run get static props just like you would run get server side props right so you would run get static props like get server side props but how get static props differs from this is that it is intelligent you can tell it to store this result now because you know let's say you had 35 million of these routes right it's not feasible to build 35 million pages up front so you can say that hey we're not going to build anything at all and whenever somebody visits it then we'll just build that page and keep it in the cache or keep it in the memory so when somebody with a store number uh let's say 999 you build this page again get static props gets called and you know it is saved for other people so now when somebody visits store 999 again what happens is that this is served served scrved immediately as uh you know a static build static page so cool because now a single visit a single visitor has to pay for that cost of building it once because you know if this is involving a lot of database calls and here and there this might take a couple of seconds and once a single visitor has taken that load on himself or herself a million other people who visits this page will have immediate results right because this page has already been built so that's how in a nutshell you can make use of get static props in the next video from the next video onwards we're going to be learning about different ways how you can block rendering how you can fall back to a loading sort of rendering we're going to discover you know just talk about all the stuff from the next video onwards so don't worry about that so yeah that's pretty much it for this video i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just discuss about get static props but technically so we have seen get static props how it works internally and on a theoretical level but let's just see what this function consists of so first things first i'm going to go ahead and rename this back to index.js because there's a major difference when you're using get static props in a dynamic versus a you know just a string based route so what i'm going to do right here is just going to return props something like this and i'm just going to console.log context now surprisingly what you're going to see right now if i refresh this you're going to see if i go to the console we have only locales locale or whatever how you pronounce it and these three props present or these three values in the context present where are the requests and response and you know all that good stuff query and patterns where are those values well you see when you are using get static props in a string based route that is you know in a static route what next chase is gonna do is it's gonna automatically on the build time on build time it's gonna generate a static uh html static html plus json payload of this particular page so that it never has to execute javascript again right and how it can do that well because you know you have just have a single route and given that next gs is not providing you with request response for adding any dynamic stuff and adding any funky stuff depending on how you are accessing it with what headers and what cookies nextjs can safely generate a static html and a json payload right so if you are looking for adding any dynamic stuff here that is probably not the best option the best option again would be get server side props however let's not you know let's not get completely discouraged on this because there is a good option there's a good way to get uh this stuff which you're going to see later on but for now just realize that get static props is pretty much um a place where you can perform db calls you know network requests without being course binded um any sort of stuff require require files which is js common js syntax or dynamic imports whatever you want to do you can do all that stuff right here right and once you're done with that once you return it as a props of something true again once you do something like this you can access this uh just like usual right so this is this is more like of a you know you are generating a page but it requires a little bit of dynamic stuff i can give you a quick example for this is that for example let's say you are creating a page where you want to show number of registered users you have right so you can create a db call here await get db and you know you can create db call and you can fetch user count the weight db dot total users right something like this and then you can return this user count like this and you can just have a user count here sure it will be generated on the build time and we generated once but you know when you are building it again or we'll see another way when you are building it again you can pretty much um you know just go ahead and show the user your total number of registered users on the uh without actually hitting the database on every single request right so if you have a million visits on the website you just have to hit the database once when you're building it and that's it why because rest of the wizards are automatically served directly from uh the cash or the the static build which is already there all right now comes the interesting part that is the revalidate option so next js comes with a very very interesting option called revalidate what does this mean this means that the seconds which you supply here let's say i have 10 seconds right here the seconds which you supply here this will attempt to create this page again in at most 10 seconds let's see what that means so let's say this is 1 2 3 4 5 6 7 8 9 10 right these are 11 12 13 14 15. these are let's say 15 requests which are coming on our websites right so these are i will say these are requests request right and let's say this is the time at which those requests came so i'm going to say this came at zeroth second this came at uh i don't know fifth second this came at six second this also came as six six six this came at eight this came at ninth ninth this also came at nine this also came at ninth this came at tenth this came at let's say fifteenth 15th 15th all right so what's happening now is that once once we build uh once we build this particular page let's say the build process is done we have created a single page we're going to have version right so we're going to have let's say version versions as one two three four five as the incremental versions of the things right so the version one is the build version of the page version two is when the page is again built thanks to this revalidate parameter version three is again when it's built next version right so let's see which user will see which version so what's gonna happen on the first that is the first visitor because it he or she visited at the zeroth time they're gonna see version one the fifth second we'll also see version 1 because we have 10 seconds as the parameter here the 6 will see one uh this will also see one one one one one everyone would see one up till this point now what's going to happen is that this person right here which arrived at the 10th second is also going to see first version right and all these versions are shipped very very fast to the end user why because they are already generated they are already bills of html plus json so you know they're just sitting on the disk just to be served right and if you're using versal or anything like that they are better they are on cdns so all of them would see version one but something would happen here something will happen right something magical will happen at this point because 10 seconds has passed and next years has just released received a request what's going to happen is that next year's backend will start creating the new version of the page that is it will start calling the subway dv it will get user count again it's gonna create the page again it's gonna you know update the html and json so assuming that it happens at uh let's say it completes at 12 second let's see if you have a visitor at 11 second if we have a 12.5 12.5th visitor at 11 second right let's see i'm a little confused with the spacing and everything but let's say this is the point where it gets completed right so this visitor would still see the version one why because this is not ready yet however once it's ready now we are shipping version two so this person would see version two this will see version two version two and so on right so i hope this gets the point across this parameter right here this is interesting because what if the request never came after the ninth second let's see what happens in the in that case well you see that next year says that hey i would attempt to revalidate the page once at most in this duration so what does this mean is that it is saying that i will at most generate only one page in 10 seconds it's not saying that it will generate one page every 10 seconds there's a difference it's sync it will generate one page at most uh uh you know in 10 seconds so this means there is no timer on the back end which is running every 10 seconds and it's triggering a page update nope that's not this happen that's not how it happens this revalidate parameter you can think of something like this it can say that hey i reval last revalidate re-validate is let's say utc timestamp 0 why not let's say uh once we have this fifth this request coming up right here so we're gonna have last revalidate uh still zero right because well this request does not make any change but next year is checked on this request then again on this request this request on you know on the ninth request till the ninth request last revalidate validate is zero and you can you can just go ahead and maintain a now counter as well now five now nine right so next year says that hey now minus last is less than 10 so i'm going to skip now minus last is less than 10 so i'm going to skip now minus last is less than 10 so i'm going to skip right now what if the next request comes after an eternity let's say at hundred time stamp so what here what happened here nothing nothing happened here that means nobody requested and no page got generated as well no page got refreshed as well because nobody visited this route next js never checked the last revalidate and the now counter that means it never took the difference to check if it has to revalidate and that means this function never got called so now at this particular point next js is gonna still serve version one to the user but it's gonna see now is now minus last is greater than 10 therefore revalidate and for the next request onwards or assuming that that completes perfectly it's going to say last value date is hundred now is 102 so you know one zero two minus 100 is less than 10 so i'm going to skip so i hope you understand how exactly this revalidate parameter is working and how uh you know this at most statement works this is super super important to understand because um you might think if you have a smaller value here you might think uh you know you're bombarding your server every single second or something but nothing like that is happening right in fact if your website let's say if you are running a news website or you know some life counter this is actually a pretty solid uh you know a way to go about because let's say you have 10 million or like not really 10 million let's say you have 100 000 people per second requesting this page so if you have server side props get server side props that bad boy is gonna perform a hundred thousand requests on your database every single second which is bad right which is bad bad depending on you know what your server configuration is and how you have configured load balancing and everything however if you are live with 100k requests a second and you have get static props with one second revalidate oh boy you are in luck because now you just have one request per second on the database super awesome consider this you are designing an architecture where you are getting a hundred thousand requests per second versus one request a second and uh you know at most people will be delayed by a single second of information here right so if you're maybe like if you're creating a website or a life counter for cricket or anything i mean that's a pretty solid deal right because you know you can afford to have a single second delay versus whenever somebody is visiting or refreshing your page they get pretty much you know your server gets pretty much down because of so much load so i hope that puts things in perspective a little bit how this is helpful how this works and all that stuff we're gonna be discussing a little bit more on get static props and the additional function which it brings in in the next video so that is all for this one i'm gonna see you in the next one really soon so what is going on everybody welcome back and in this video let's just take a very quick look at a get static props example before we move forward so i have created this simple simplest as couldn't get more simple user count uh probably a bad name but i have deployed it so anyway so this is a math.random variable and uh you just display it on the home page right on the index.js and this is deployed on versil right we're going to come to deployment in the end but i have deployed this on versailles and i have also opened this in the local as a local server now one thing you have to remember when you're developing with nextgs locally next chase is going to run get static props every single time on every single run so if you refresh you're gonna see this math.random value changing every single time right as you would expect because well it is running on every single one so this value gets updated every single time that's why we are getting a different value however on production because we have revalidate parameter it's gonna well run once but it's gonna revalidate the page at most every five seconds just like we discussed in the last video so now if i refresh this you can see well if i refresh if i keep refreshing it you're gonna see the value is not changing right however if i refresh it after five seconds for example the value updates and now it's gonna stay same for at least five seconds then it updates and it's gonna stay same so you know you can see how this is pretty much working and that's pretty much all i wanted to show in this short video so that is all for this one in the next one we're going to be discussing about get static parts again just like i said which is again a little bit of extension of get static props itself so that's all for this one i'm going to see you in the next one really soon hey everyone welcome back and in this video let's just go ahead and take a look at get static parts right so this is an indi additional method which is sort of handy with get static props and actually make data tree and i'm going to tell you why this is required consider that if you have a route something like i don't know sharp id right and you're trying to implement get static props on that well first things first you need the id parameter to fetch the stuff right to fetch that particular information against that so first thing is that we need patterns somehow in get static props second thing is that you know next year's like i said likes to run get static props on build time right so if you even if you get you know some sort of way of using these patterns and then you know doing this doing data fetching using patterns you know if you want to probably build a part of your website on the build time there is no way next years can know what what ids this will take right it might take one two three four five till hundred it might take some strings and it could be anything right so you need next shares you need a way for for informing next that hey i want maybe i want these these these pages built on the build time and then maybe we can fall back to this particular approach which we talked about that you know people will come and then we'll build and store it and then we'll just make that happen so in order to make that thing possible we have a function called get static pages right so this export function this get static pages is a function which is going to allow you not really pages it's parts right it's going to allow you to provide that information to nextjs that means you're going to return certain value from this particular thing and precisely we're going to return paths as an array this is going to be a value it will contain information on what all pages you would want to be billed at build time right ahead of time and anything else which is not present inside this will either 404 or will be built dynamically depending on a bunch of other parameters as well but first of all let's see how you can make use of this so this will be an object an array of object right and right here you're going to specify you're going to start writing patterns and then patterns would also be an array of object patterns p-a-r-a-m-s and patterns right you're going to start writing here and yeah the biggest requirement the biggest biggest requirement is that you need this route to be dynamic so i'm going to shift this to id right and now you can say id which should match the name of your file or the dynamic part of the segment which you're targeting and then let's say uh product one right then you can have an id of product two for this one and then maybe like id of product three for this one right so you have all these parts available to you and if you just leave it like this what's gonna happen well you have to specify another parameter called fallback let's say you have a fallback of false so in this particular configuration when you push it to production when you run next build what's going to happen is that on the build time next years will run get static props with product one well not exactly product one but you know you get the idea i'm gonna tell you you can extract you know patterns from this context as well so it's gonna run it with something like patterns id product one right that's that's more like it with a bunch of more options it's gonna run it with product two it's gonna run it with product three this is gonna spit out some html plus json this is gonna spit out some html plus json this is gonna spit out some html plus json right next yes is gonna run uh all this on the build time remember this is all happening on the build time and we finally store all on disk cdn whatever right and then serve it immediately whenever somebody comes this is because of fallback falls right if you have if you have fallback true something interesting happens well we all obviously uh we do the same thing again but this time actually let me let me just discuss fallback falls again i guess we did not complete it so now if you come to a page which is something like shop id or like product id product 4. if you come to this and remember we have fallback false this will go 404 not found why because you mentioned that hey i don't want any fallback for any non-supported page right that means you're on your own you're going to get a 404 automatically now if you have fallback true something interesting would happen on this point when somebody visits this this route next chase is going to see that hey i don't really have an html plus json payload for this particular route but you know get static parts actually told me that the fallback is true so maybe i should go ahead and ask get static props what's up so when you visit this what's gonna happen with fallback true is that next year's is gonna load the page with uh you know you can get the nexus router use router you can import the nexus router use router you're gonna have a router that is fallback property set to true and i'm not really entrusted into this into explaining this why because first of all this has already been explained in the basics course and secondly there's a better option now with next years so right now as long as this is true on the client side right now uh react uh not really react next js uh get static prop is executing right and the moment it becomes false that means you're here get static props has executed and you have the data from the props automatically and this will be stored again you can think of it getting added sort of getting added like this so that it does not have to build again right that happens to fall back true so let's take a quick example on this so i'm going to go ahead and return a loading right here and i'm gonna say loaded here this could be like h1 only why not and we have product one two three four which is perfectly fine i think we just need to import the router import use router from next router i think this is a default yeah not really right so once we have that let's just go back to the browser and go to product one hit enter you're gonna see we get if i refresh this we see loaded because we already are generating product one automatically if i have product two we see loaded which is fine product three and four will also show loaded but if i go ahead and visit product five you're gonna see that if i refresh this for a split second i get this loading right you can see that that does not happen with product 4. product 4 loads immediately but product 5 right here we get a split setting split second loading why because if you go to xhr and refresh this you're going to see product 5.json actually is loaded a split second later i'm not sure if i can show that let's toggle to slow 3g and see so now if i refresh this you're going to see i get loading for a little bit longer let's hope actually it's downloading the whole js bundle as well in the development so that's why it's pretty slow but what you're going to see eventually is that the product 5.json is dynamically generated when you have the fallback true and it does not wait for it being generated it's just gonna throw something down the wire right so that's something the client can see at least something which is kind of bad if you want to have a full blown experience on the first load right so you can see it shows loading for a while and then we make a request and then it shows loaded right so how would you make this uh a seamless experience in terms of uh you know for example if you take a look at product 4 product 4 loads immediately just like we discussed right so how would you make it same for product 5 well there's a new mode called blocking right here and what fallback blocking would does is that it will not send any response at all unless the get static props has executed right so now if i refresh this on product five hit enter you're going to see we no longer get loading anymore and the reason for that is that you know this actually runs uh the static props first of all and then sends it down the wire that means it's fallback is never true so the pro of this pro of blocking is that no flashes flashes of loading or loaders or you know missing content the con of blocking is again of course the first visitor and only the first visitor right because you will be storing it on the disk and all that stuff the first editor will have a little delay that's it which is not a big of a con to be honest if you think about it so that's that's pretty much it so in most of the cases you would probably want to use fallback blocking unless this is very very slow right unless this is very very slow you would probably want to use always blocking so yeah i mean that's pretty much how uh get static parts work very simple method not really have a lot of bells and whistles just paths and fall back mainly and fall back also i would highly recommend if you do not know upfront all the parameters you can set it to blocking a very common convention is to have empty paths here and have fallback blocking so that means now every single page route would be created on the runtime and then stored that means it will not be created again and again and then stored and will be refreshed depending on your revalidate parameter so i hope now you can see all the parts coming together and building together right so that is pretty solid infrastructure and framework which next year's provides you out of the box so yeah that's pretty much it i think a lot of knowledge a lot of concepts a lot of things if you are learning it especially for the first time so take some time you know visit this video again if you want and you should be done with it so that is all for this video i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just go ahead and take a look at what preview mode is in next js right so we have looked on gets oversight props and gets static props and the get static parts method but there's also something known as preview mode in nextgs which kind of sounds like what it does but let's just go a little bit deep into what exactly it is and how it works so in order to do that what i'm going to do is create an api function let's say enable preview.js right so you know in apis you know how this works you just export a function like this and you would be able to set the response data score and all that stuff in an express like way right it comes with a express like json sort of method attached to the response object and so on so instead of you know you can do all that stuff but inside of your api response if you do something like res dot set preview p-r-i-p-i-v-a-e-w data and you pass in an empty object what's gonna happen is that next chase is gonna set set some cookies right so this method internally sets some cookies on the response so let's see what that is so if i go to the browser and if i go to api slash enable enable preview and hit enter you're going to see of course we get the response back but if you go to the dev tools inside the application cookies you will be able to see that there are a couple of cookies which are set you can see the first one is next review data and the second one is the pre-render bypass right if you take a look you're gonna realize that this looks awfully familiar to a jwt token right so we have two parts here the first one is next preview data and just like i said the second one is pre-render bypass next preview data is a jwt token right so you could probably just copy this next preview data is jwd token and this one right here prerender bypass it's just a random hash right random idea random hash whatever you want to call it right so what's happening here well you see if you try to decode this data right here if i try to go ahead and take a look here you're going to see that the base64 encoded part which is the central part if you do a b2a of that not really b2a a to b you're gonna see you get something like this right which again looks like a bunch of encrypted data and actually i'm not sure what this data is exactly right i'm not sure of the encryption but the point is that you can pass some data right here so you can write something true and if you go ahead and refresh this the stuff which gets set as the cookie inside this next preview data is actually that object something is true right so if you do a to b here i mean you won't be really able to see it because that is using some sort of encryption even in the data parameter but you can see it has got an expiry date with it uh not really this is not expiry it's just the time when it was created right so let's see if this is correct and yep this sounds about right yeah so what's the use of this well you see that preview mode preview mode can technically be used to have the development like behavior of get static props now what do i mean by that let me just elaborate on that so if i have export function get static props right and if i return a prop of props of you know numbered as uh math.random and let's say i have fallback as blocking right and this is this is not the place to put it it should be export function get static parts return pages is this and fall black fallback is blocking so once i do that i can use props dot number and get rid of this right and now if i go ahead and refresh this particular two for example and we have some errors extra keys returned yeah this should be parts not pages refresh and now you can see that every single time you refresh you see you get a new response now the reason you get a new response is that get static props is called on every single page refresh on development this is important right even if you have a revalidate parameter here for example revalidate uh 10 seconds you're gonna see that you get a new response on every page load now the reason for that is you're running in development mode if you push this to production and let me just go ahead and clear the cookies first of all let's do it from devtools so that you are you are able to follow if you want to i'm going to go to application cookies and i'm just going to clear them off right so if you go ahead and refresh still refresh it you're going to see that you get a new different response on every single payload page reload reason for that is that get static props this is called every time in dev mode so preview mode is kind of like dev mode on production what does that mean that means that get static props will be called every time as long as preview mode is enabled all right so let's see what that means by actually uh you know deploying this on production and i'm gonna set a revalidated parameter to like 60 seconds so that we can have a little bit of space in between of uh seeing things all right so i've just deployed this url on a versal domain and what i'm gonna do is just go to a random id right so if i go to let's say slash two and if i keep refreshing this page for example you know just leave that first blip but now if i keep refreshing this page you're gonna see that it pretty much stays the same value right i'm refreshing it again and again and it stays at the same value the reason for that is that once it generates uh you know a match.random number for the slash two route that is uh that how time on it would pretty much not run this function again right because next year's says that hey i've already generated um the particular page for that particular route so let's just use it directly from the cache from the disk it would it would generate it if i keep on refreshing it and it hits the 60 second limit which we have already discussed in the previous video but it will only generate it once at most once every sec every 60 seconds now let's say this was something of a blog post preview right you're editing your blog post with a cms like ghost or something and then you want to preview it so this is a this is a difficulty right with next yes because even if you try to you know if you're trying to set it too low then you are just hitting the um you know your server too much if you get a lot of traffic on your blog even though if your content does not change that much if you're setting this too high well you cannot really work with with a sort of draft preview mode from your cms so to fix this we have uh the preview mode which you can use this is like one use case so what i'm going to do is i'm going to go ahead and hit this enable preview api url so let me just go ahead and open the cookies part as well so right now you can see we have no cookies and if i refresh this it stays on the same particular value now let's just go ahead and hit api slash enable preview hit enter and you're going to see that it immediately sets two cookies next preview data and pre-render bypass which we have already talked about now if i go back to slash 2 right here what you're going to see is that on every let me just keep that open is that on every refresh we are getting a new number even though this is a production domain right even though this is a production domain we are getting a new number on every refresh and if you can observe the page response times are a little bit slow because it has to like you know run this function again render the tree and then pass it so once you have preview mode enabled it will always always always run this function right now the beauty of this function is that the beauty of this feature is that if you do not have the preview preview cookies for example if you are a visitor of the site it will just work as normal right so you can see uh just that was just an update to the page but if you keep on refreshing it you're going to see you get nothing but the moment you try to enable the preview again and go back to 2 keep on refreshing looks like we did not enable the preview mode refresh yeah so here we go needed a hard refresh so once we do that and now if you return to two again you're gonna start seeing different numbers again because this is just like i said renders it automatically every single time irrespective of what configurations which you have here so yeah this is like preview mode could be useful if you're developing a cms-like application where you want to have specific access you know real-time access to specific pages but that's yeah that's pretty much it if you're not developing some sort of dynamic content which is linked to a gui in terms of editor or something this will probably not be required but nonetheless you should know about this so that is all for this video i'm gonna see you in the next one hey everyone welcome back and in this video let's just take a look at what dynamic imports are in next.js so dynamic imports is pretty important and interesting feature of next years which you might encounter a lot of times if you're if you are working with npm packages and things which are browser environment specific right which require browser environment so what that means is that first of all dynamic import means that you are importing a piece of code on the runtime dynamically right so the first thing is that obviously it will not be um included inside the html of your page it will not be server side rendered on the first load right so the first communication for example um let's say i have a div right here and if i have dynamic h1 here and if i have p hello world let's do a quick uh you know demo of this so i'm going to have a dynamic h1 i'm going to explain you the syntax for this but just bear with me for a while here so let's say if i have dynamic h1 as the component and we would also need dynamics from next dynamic dynamic right so what you're trying to do here is that import this dynamic h1 on runtime so if i do something like export default function h1 and then just to h1 hello world so what do you think would happen so if you take a look at this you're gonna see you get an h1 and a p just like um you know you would expect to get right and if you go to let's say the sources or maybe like yeah the networks tab you're gonna see that this one.js file is the actual chunk of this dynamic h1.js right so what does this mean is that for example if you had something like um let's say a compute which is like an expensive compute right i don't know add it dot fill or maybe like not add a dot fill add a thousand dot fill zero dot map or dot for each x console.log x right if you had something like this i mean this is this is ridiculous but just to give you an example and if i go ahead and refresh this now you're gonna see if i go to console if i go to sources if i go to network you're gonna see inside the one.js file well you only if you could just look inside the cival but let's see if i could if i do a console.log you can see that that bit of uh you know code execution is present inside one.js which is a different file right if i go ahead and remove this as a dynamic import if i go ahead and import this in a regular way from let's say like this right if i do something like this and hit refresh you're gonna see that there is no one.js anymore there is just this uh console.log not even 0.js i think inside will get probably yeah inside index.html you can see index.js you can see the single file which ships with the whole uh bundle of stuff right now this is obviously not the production build but inside production build as well you're gonna not see any different uh request with dynamic import although it will render it on the server you know if you go ahead and take a look refresh and go to page source you're gonna still see hello world right here it is still rendered on the server it is server-side rendering but there's a big but the javascript bundle of this the rehydration you know the when the react downloads the js and tries to add all those click handlers and everything that piece of javascript is only downloaded um when it is required right so what's the use case of this well one use case could be that let's say you have a user panel right and let's say you have a or maybe like not really user panel but authenticated panel and you have non authenticated panel right and you do the stuff so you know leave the uh compute part already like even if it is a lot of javascript that will also be good for us so if you have uh authenticated here and non-authenticated what you can do in react is that you can say hey if user is authenticated then show him this panel otherwise show him non-authenticated right something like this you can do something like this and the way it will work is that if the user for example on server let's say the user is considered always authenticated let's say if the user is authenticated you're going to always show this component and if the user leaves your website you're going to always keep on showing this component and you will never show the non-authenticated component how does this help this helps in the way that you never really download this non-authenticated panel bundle right so that's a huge um data saving if this is a big file if this is a big js file so yeah that's pretty much it on the dynamic import without dynamic import with server side rendering there's also a variant of without server side rendering we're going to take a look at that in the next video but i hope this gives you context on how dynamic imports exactly work how the split split the files into different chunks and how they are still server-side rendering but with a different approach right that is the javascript which uh enables the dehydration and everything in the component is downloaded differently from the main bundle so yeah that's pretty much it for this video i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just take a look at the next image component which is again a very interesting component from nextgs and like one of the most exciting features for me at least um when it came out so what image component is is that i'll just show you an example real quick let's just go ahead and actually let me see if i can grab a screenshot and if i go ahead and grab the screenshot for this and place it somewhere inside public let's say right here right so if i have a screen oops if i rename this as screenshot right and if i go ahead and take a look at for example public and then if i do ls lhs or screenshot you're gonna see that this actually weighs 111 kilobytes right fair enough let's just go ahead and use an img src of uh you know screenshot.png right here right and if you go well let's just get rid of all the stuff right and if you go let's just remove this and if you go ahead and take a look you're going to see that it pretty much just embeds the image just like you would expect it to right now the problem right here is that there are a bunch of problems first of all if you use something like s3 or you know some other provider which is just raw file provider and not optimize images then you waste a lot of bandwidth right so this is like a huge problem second because of this your images images are heavy uh you know not scaled therefore slow for user right this is also a big problem right and third one is that you are lacking images for different different dimensions and you know accessibility and all that stuff because right now you can also see that we are not specifying width and height attributes so that means there would be a you know cumulative layout shift cls which which stands for like i don't remember the exact spelling cumulative layout shift which just means that how much your page is shifting within a span of let's say i think it's 50 milliseconds or 500 i don't remember but the more the page drastically shifts the worse the score is for the cls factor right so there are a lot of optimizations which can be brought in inside images when they are embedded and images are like a heart of almost every website there are a lot of images um pretty much anywhere on any website right so what next js did is that it gave you the option with nextjs 10 to have all these problems fixed with a drop in replacement of the image component from next so if you import image from next image and if you try to embed this like this with an image src what's going to happen is that if you save this you actually have to specify the width and height as well but yeah you have to specify so let's just give it a width of let's say one two eight zero you can also use numbers and a height of 720 right you can technically disable this as well if you don't want to give this but there's a pretty good reason you should so if you refresh this now you're going to see that first of all your image is resized according to dimensions which you gave right and observe that this is actually a you know optimized version of image as well how do i know that let's go to networks tab clear this out refresh image and right here if you go to headers you're gonna see that the content size let's see let's see if i can save this um on the desktop as the image name so if i go ahead and do ls lahs of desktop image dot webp you're gonna see this is in fact 28 kilobytes right so what happened is that next year is detected that well this browser can support webp format and we want you know uh an image which is not um that large we have already specified the dimensions one two eight zero seven twenty why not just compress it a lot right and just make sure this is good so you got an image.webp format directly from the png or jpeg whatever you're using and it is much smaller right this is 28 kilobytes 28 and that was 111 kilobyte right the original one so you got all that optimization automatically out of the box in fact if you take a look you're gonna see that it uh you know specifies a bunch of options as well and one another another one interesting option is that it lazily loads images that means if the viewport height is not um you know if the viewport height is not that much that means that the image is visible it will not show that image so if i go ahead and create this multiple times a bunch of times you're going to see now if i refresh the page you're going to see in the networks tab inside a maid section we have not loaded the image yet right the image is not present but if i scroll down a little and make the image visible you can see that immediately it loads right just before the image is visible right so if i close this refresh this close this refresh this you can see it's not invisible right now and it is now visible right so that is pretty cool again that happens because of the uh nexus optimization and there's also native browser support as well for this such such behavior but i think it's very limited right now to chrome only but anyway this is how this works right it also specifies it also gives you you know a 2x version basically a lot of optimization out of the box so you can just feel free to replace all your img with image given that you have width and height otherwise there are a bunch of other dimensions as well other other sort of properties as well so you can specify layout fill and right here you can still get that exact same behavior which you pretty much get but i guess in this case the width and the height are pretty bad for the container but anyway you might want to customize this with css now so yeah i mean whatever happens what you can think about what you can do is you should always use the image component because it optimizes it scales it makes your images work much much better on an xjs website one caveat of this is that you need to have a next share server running that means uh you need to have a next share so you cannot really statically export this why because if you go to networks tab you're gonna see it request a particular uh you know api endpoint which is specific to next year's framework and this endpoint will not be available if you are not running a next year's node server on the back end right so that is sort of a caveat but this is also um you know fixable in in a way which we'll discuss in the next video and i'm also going to introduce to you with next.config.js file in the next video so yeah stick along so that is all for this video i'm gonna see you in the next one hey everyone welcome back and in this video i'm gonna introduce you to a couple of things the first one is obviously we're gonna continue with our next image component and the second one is the next.config.js file now this file you have to create it will not be present by default but this is a hard coded file again the name is hard coded into next year's framework and whatever you export from this file has special meaning to next year's framework right and it shapes the behavior of the framework and of course uh this file is just red just like environment variables this is read on the boot so if you're making any changes you got to restart your server so what i want to do first of all is i'm going to show you that this is fine this is absolutely fine that you are referring an image with a relative path but what about if you want to embed an image which is from a different domain right let's say if i go to courses and [Music] well this will also be a nexus embedded image but let me just go ahead and try to extract out the uh real image out of it so if i go ahead and do a decode uri component i will be able to see that right so this is like the raw image which is hosted on s3 so now if i go ahead and try to embed this like this what you're gonna see is that it saves me invalid src prop because the hostname creatorassets.codam.com is not configured under images so what does this mean is that if you are trying to include any image which is not absolute path right or which is not relative path not absolute then you have to you have to add uh white listing for that particular domain and how you do that is that you go to next.config.js create an images uh key and add that to domains right so in this case it will be justcreator.codam.com now remember this is important if if you are hosted your website on codedam.com as well right so let's say if you are hosting an image on codedone.com itself and your website is also running on codedum.com if you use a direct absolute url you still have to whitelist codedam.com that means even if your website is deployed on codename.com and if you're using like this you have to whitelist it right if you're writing any sort of domain name here you have to white list it otherwise this will not work it will complain it will throw an error in development and in production i guess it will just it will just crash i don't remember the exact behavior but it will not show you the image right so once that is done you know for this of course we just need the create a dot code down part and if i not really creator but creator assets right so if i go ahead and replace this and if i go back right here and if i restart the server you can also see it tells you to do that so now if you go ahead and refresh this what's going to happen is now it is loading that from the remote server it loads it first of all inside its own memory optimizes it for the first time and from the next times onward it's just gonna you know just make use of it from the cache so again super helpful super powerful um in terms of resizing and you know just having the best possible image served to a particular client highly highly recommended to make use of um you know the behavior which image tag provides you it also comes with a bunch of other attributes i did not go through every single one of them you can pretty much just take a look at the documentation if you want but the most common ones i have just listed you're going to just need width height and src you can also specify the loader which is an interesting part you can specify the loader which you want with the image component and what do i mean by that that means that right now you can see that well it just fall backs to uh you know the local host so if you can observe what's happening here is that it takes your url it takes your url right here copies it and pastes it paste it right here right so this is the image url and then it specifies the width and the height as well if it wants to this is quality parameter so what you can do is that let's say instead of having this hosted on nexus the image optimization service let's say you have bought it from some other service provider right let's say mgx or whatever you pronounce it right then you can also specify a custom loader for that and the way you do it is that you create a function you create a function called loader and it's going to accept some arguments it's gonna accept some props and the props are src width and quality right pretty much which are passed um inside our this loader which was before right i just have not copied the url but what you're gonna see if i console.log src width and quality and if i try to return for example http uh my custom service dot com slash url uh url is equal to src what you're gonna see now if i specify this as the loader for this particular image you're going to see if you refresh you're going to see it tries to load your service from a url like this my custom service url and then that so you can have all that custom logic of caching and everything on your own services as well if you want if you don't specify this this fall backs to um the internal next share service this is useful if you're developing an a completely static site where you don't really want the next share server running on the back end right so that will help you save a bunch of money if you don't really want to run a node server just because of image compression so yeah that's pretty much it for the image tag basically we have covered all the important stuff you can figure out other details of the smaller details on the way as well but that's all about it so that is all for this video i'm gonna see you in the next one hey everyone thank you so much for watching the whole course till the end if you are interested in more content around next year's mastery learning path you can go ahead and subscribe to the code damn lead membership using the link in the description you're going to get 10 off on the membership which unlocks all of the next year's mastery this not only just includes video courses but hands-on practice mentorship support from me you get my whatsapp number and access to code down accelerator groups in the future so yeah i mean if you can afford it and if the course benefited you it will mean a world to me if you go ahead and subscribe to the membership because it helps me make a lot of more content for free for people who cannot afford it and it helps to keep the platform running as well so that is all for this video and i'm gonna see you in some other course [Music] you
Info
Channel: codedamn
Views: 33,336
Rating: 4.939189 out of 5
Keywords:
Id: EJVGzyWSCBE
Channel Id: undefined
Length: 114min 0sec (6840 seconds)
Published: Sun Jan 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.