Next.js 12 - Middleware & Edge functions explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
next chess middleware and virtual edge functions were introduced earlier this week in the next js con for the past few days i've been trying to wrap my head around how the middleware and the edge functions work and full disclosure i'm not saying that i am understanding them 100 but i think after playing around with them quite a bit i now got a pretty good understanding on how they work and even though i might not understand them 100 i still felt like i should make this video because it took me quite a while to actually get where i am now in understanding the middleware and edge functions and i'm happy if i can help you guys to actually understand them much quicker than i did so in this video i will first explain you how the middleware and edge functions work and then we will also take a look at some code where we first create an api that is protected by basic authentication and we will use middleware to implement that basic authentication and second we will actually deploy and compare a normal api route function and an edge function so if you are ready to go hit the like button below and let's get started first let's take a look at middleware and i also mentioned that middleware and the edge functions both are still in beta so there still might be some bugs along the way so middleware is basically a function that runs before a request is completed so before api route function is executed or before the code for a page is run and we can modify the response based on user's request so for example we can get the user's geo location from the request and then redirect the user based on that if you deploy your application to versal the middleware will run on the edge functions which we will talk in a minute and if you want to host your application somewhere else that is possible too because the middleware works out of the box using the next start so that's in short what the middleware functions are so they run before the request is completed you can modify the response inside the middleware and they are deployed as edge functions if you deploy them to versal ok so that was middleware so what's the edge then well edge is the microsoft edge web browser which is fast and secure browser that helps you protect your data and save time and money i'm sorry i couldn't resist okay so what's the edge the edge functions uh well the best way i found to explain what edge functions are is to compare them to serverless functions let's first recap how serverless functions work so when you deploy a serverless function to versal it gets deployed to a server somewhere in the world for example in san francisco then requests made to that function will be executed in the server in san francisco so if the request is made somewhere geographically close to san francisco then the request will be pretty fast but if you are making a request to that function somewhere that is far away geographically from san francisco let's say for example in helsinki finland then the request will be much slower and this is where its functions can help us so in simplicity its functions are serverless functions that run geographically close to the user that makes the request making the request very fast regardless if you are in a san francisco or in helsinki when you deploy your nexus application to verso all the underscore middleware.js files or the middleware functions will be deployed as its functions so that function will be deployed to all regions around the world so instead of the function sitting on a server in san francisco it will be actually sitting on multiple servers around the world and i found this tweet that explains this very well in my opinion so jamesquick asked if someone can explain the edge in context of web development and there was a couple of good answers right here one by jeremy morgan saying yes it is web apps deployed to servers geographically closer to the visitor so folks in other countries or areas can access it with fewer network hawks so that pretty much explains it and then there was also answer by tweets by colin saying that the files in your slash api folder on next.js are usually configured to run in a single region on verscell and right here we can open up the different regions and then also that the new underscore middleware files run in multiple geographies by default and the region closest to your user will respond so this leads to less overall latency and then there was this one more answer right here by brently harris this is in my opinion very good analogy of this so first you must understand the cdns are like putting the things you want in wall marks all over the world so you can just go get it rather than sending it to you via fedex from and warehouse in oklahoma and then edge computing is putting not just objects in walmarts but whole services in each one and they are all exactly the same so this was very well said in my opinion so now let's take a look at some code and how we can actually use these functions so i have my resource studio code open right here and i just initialized new project with create next app and first let's add a basic authentication to our api routes using the middleware so i'm going to open up the pages folder and the api folder and right here we have the hello.js route that is the default api route and let's add a basic authentication to this api route so in order to add middleware i'm first going to create a new file called underscore middleware and the way we can use middleware is to export a function called middleware from this file so let's add that and the function gets the request as a parameter and now let's add some logic to check the basic out in the case i'm just gonna copy paste some basic authentication code here because it's really not relevant how we do it but where we do it so i'll paste it in and let's quickly go through it so inside the function we first get the authorization header right here then if the authorization header is set we will parse the username and password from the header and then we just check if the user equals admin and password equals to password and if they do then we just return this next response and call the next function and what this next function does is it returns a next response that will continue the middleware chain and then right here if the basic authentication was not set and the user or password didn't match then we will return a new response saying that authentication is required so let's save this and i'll open up my postman and let's make a request to that api route oh and we need to start our server and now let's try again okay we get the auth required message which is good because we didn't define the credentials yet so i'm going to open up the authorization tab and from the auth type i'll select basic alt and for username i have admin and for the password i have the password now let's make the request again and looks like we get an error and oh yeah we forgot to import that next response let's do that save it and let's try again okay now we get the json response we want it and if i change the username for example and make it again we get the auth required messages so it's that easy to add basic authentication to your api routes and now the cool part in this is that if we want to add for example a new route inside the api let's make a new one i'll just call it hello 2 and modify the response like this let's save it and try to make a request in that so slash api slash hello2 we get the result and again if we change the credentials so they don't match and make the request we get the auth required message so by only adding this middleware file we get the authentication to all endpoints inside our api folder if we didn't use the middleware we would probably have to do something like checking the authentication inside every route so this is much easier and convenient and last let's compare the edge functions and the normal api route functions so what i'm gonna do is actually again copy paste some code inside here and then go through it okay so what i did was move the hello code that we just made inside a hello folder and created a post folder over here and right here we have two folders the first one is called edge and inside of it we have the middleware file and then just post js file which is basically an empty handler and inside the no edge file we have just the post file and inside of here we have some logic tool so the idea here is that we make a request to the api with a post id and as a result we get the post title and for getting the post title i'm actually using these jsonpace holder api that's a free dummy api that you can query for example posts and when we make a request to this api let's try it out so if i replace the post id for example with one and send it we get this json object as return and for this example we will use the title property here and just return it from our api so inside the no edge file we are getting the post id from the qra parameters then we just check that it exists and if it does we'll use the fetch to get the json and then we return the title so that's pretty basic stuff you would do inside of an api route but with the it's folder we actually do all this inside the middleware function so right here we have the middleware function export it and inside of there we get the url from the request and then from the url parameters we will get the post id i know this is a bit ugly but hey sue me then we check that the post id exists and if it does then we'll use fetch to get the post as we did in the api route and then actually return the json right here in the middle aware so we don't even need to go to the api route and we can return the json right here in the middleware and as you can see we can use fetch here because the middleware uses the strict runtime which supports standard web apis so this is our middleware and what i'm going to do now is actually deploy this to versailles if you don't know how to deploy your app to versal don't worry i have a video about it so you can check it out from there okay i have my project opened in virtual dashboard and it is deployed and i'm gonna click the visit button and copy paste the url for this and then switch back to my postman make a new request paste in the url and then the route we want to check is let's start with the no edge route so we will go slash api slash post slash no edge slash post and then let's add the post id like this and let's make the request we get the title as response so that's good and right here we can see how much time the request takes so the first one is always slower because it's caching it so let's make few more so as we can see it's about 250 to 30 like 200 milliseconds give it a take 200 to 250 and if we change this to the h one so this was the one that runs on the api route the basic api route and it took us a little bit over 200 milliseconds and now if we change it to edge and make the request again now it's making the request to this endpoint and it's doing all the work inside the middleware function so let's make a few more requests to see how much it about takes so let's see the first one 300 okay 80 70 130 80 1880 like we see it takes around 100 milliseconds and with the no edge version it took like 200 milliseconds so right here i know this is not like the best way to test this but just to give you an idea how the edge functions work so right now the its function is actually deployed on multiple servers and when i make the request it actually makes the request to the server that's closest to me geographically and when i'm using the no edge version so we are not using the edge functions like this the request is actually going to probably that san francisco server or washington server that's pretty far away from me so this way the edge functions can be much faster than the normal api route functions i really hope you found this video helpful and if you did please leave a comment like this video and hit the subscribe button below
Info
Channel: Tuomo Kankaanpää
Views: 24,183
Rating: undefined out of 5
Keywords: next js, next js tutorial, next js tutorial for beginners, next.js, nextjs, javascript, middleware, edge functions, next js edge functions, vercel edge functions, edge, vercel, next.js middleware, next.js 12, next js 12, new features, serverless functions, next js vs react, next js react, next js routing, next js website
Id: NlBSheYPKkg
Channel Id: undefined
Length: 14min 13sec (853 seconds)
Published: Fri Oct 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.