NextJs Middleware | How it Works & Real Use Cases

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this lesson we're going to talk about next Js middleware now if you've ever built a server with express.js you might be familiar with the concept of a middleware which is basically a function that runs or executes before you send a response back to a request coming into your server now nexjs has a similar concept it's actually named also middleware which allows you to run code before a request is completed so let's Dive Right into this as I mentioned using a middle where you can run code before a request is completed so you intercept the request and you can do different things inside of this middleware function things like rewriting the request URL or redirecting to a different URL modifying cookies and headers which we're going to see in action or even respond directly from your middleware you can return or render a page component or respond with Json like an API endpoint now it's good to know that middleware runs before your cached content or your route segments are even matched so it intercepts the incoming request before any of your cache content is actually returned therefore it can be useful for things like Authentication we're going to actually implement this in the next module where we talk about authentication using the next auth package or the clerk package in both we're going to also actually implement it with middleware as well so you can see that there as I mentioned you can redirect or rewrite based on the geolocation of the user if that's available to you you can modify the request or response headers rewrite and manage cookies you can render page or components respond with the Json block based on the IP or do things like a b testing we're going to see some of these examples in the code so we get comfortable using a middleware but you get the idea you can just execute any code before the request is actually completed for your application now how would you go about creating your middleware you would put in a middleware.js or TS file in the root of your application to define a middleware and from this file you would export a function this function can also be an asynchronous function if you need to evade something inside and you have access to the request object which is an instance of the next request which is an extended version of the web request API we touched on this in the previous lesson briefly and you can read in the documentation to see um what actually you get out of this extended version of the next response or next request they provide helper functions and properties that you can use inside of your middleware or inside of your route handlers Now by default this middleware file is going to run for every single path or every single request that comes to your server and now you can limit what paths or segments this middleware is going to run on in two ways you can either use this custom matcher config like the config viewer exporting here so you export an object and match the specific path you want this middleware or function to be executed on the second way that you can decide what happens or for what paths this middle of the run is with a conditional statement so let's just see the matcher config first and then we're going to also see the conditional statement so a matcher as I mentioned allows you to filter middleware to run on a specific path not for your whole site because by default it just runs for your whole project now you export a config object with a matchup property on it and you can specify the specific path that you want this middle there to run on you can also provide some options to this we're going to look at the options in a second but before if you want to provide multiple path you can pass in an array like here we are matching about or dashboard we're also passing some parameters and some regular expression characters here we're going to see this in a second but get the idea and you also this matcher also as I mentioned supports regular expression so you can do things like negative look ahead so here you're saying match this middleware for every route except for API routes or anything that inside my API folder for the next static features or your static files for images that the next.js server is serving up or for the favicon so you can for example in authentication typically you don't want to hide the static or image or favicon behind authentication so you can do a negative uh look ahead we're going to also implement this when you're using clerk to see this in action one thing to note is these values that you use inside of these matchers they should be static values so you cannot use variables that's something to note now let's talk about how you can config these paths now it needs to start with A4 slash so that's the first thing second thing is that you can use name parameters like this so if my matcher says for slash about and then this path parameter it is going to match slash about for slash a or slash about four slash B but it's not going to match about for slash A and C because we're only providing one segment after this about so it's going to match about four slash A or B but not both if you want to also provide anything that comes after you're about you can just provide this wild card character at the end of your parameter here to match anything that comes after forward slash about so this would match about four slash a b and c it also would match for slash about four slash a so this star character or asterisk character is zero more so it's your regular expression Wild Card character and it defines that this thing that comes before it can happen zero times or more times so that's why you can have more of these segments now the question mark is zero or one so it's optional when something is optional and the plus character is going to be one or more so at least one or more of the character that comes right before it so in this case was this named parameters so using this type of regular expressions or name parameters you can have granular control over what paths and segments inside of your application you want this middleware function to be executed as I also mentioned it supports regular expression so you can pass in your regular Expressions inside parentheses like here so this practices with this regular expression is the same as writing this named parameter with the Wild Card character so here we are providing this period or dot in regular expression this can be replaced with any alphanumeric character and we are setting a star after it so which means it can be zero or any or more of this alphanumeric character so therefore it will pass it would match for slash about four slash about four slash a and also if it is uh having B and C after just like here so it's the same as what we did up there but here we are just using regular expressions now if you don't want to use a config matcher so remember this is this is how we Define uh with these matchers how we Define what paths or segments we want this middleware to run on now the second option is using a conditional statement so inside of our middle verb we're just actually reading the path name from the next URL so this is one of the useful helpers that you get on the request object is this parsed next URL you can get the path name out of it and here we're checking to see if if it starts with for slash about if you're rewriting it to a new page which is about two or here we're rewriting the dashboards to a new URL that this request URL is going to give you the request URL which contains the base and using this new URL which is the web API you're creating a new URL it uses the space and then it adds this path to it and we're just rewriting or redirecting to that path so as you can see here we're not using any matchers in this file it's just we're exporting this middleware function but instead inside of the middleware we're just deciding what we want to do conditionally fit this if condition statements based on the path name now as I mentioned you can use cookies set cookies or modify headers on the request and response object inside of your middleware function specifically on the incoming requests for cookies you have access to these functions get get all set delete hasn't clear you can get a specific cookie value get all of the cookies set a specific cookie delete a specific cookie check to see if a specific value actually exists on the cookie or clear your cookies and similarly on the outgoing responses for cookies you have access to getting setting and deleting your cookies if you're going to actually see this in the code but as an example here if you're reading this next JS specific cookie on the request object which if it exists assuming that if it exists it's going to return an object with a name that sets to that key that we are trying to read the value whatever value the cookie has and then the path name which displays cookies set on if you call to get all function on the cookies it's going to return an array of objects with all the cookies that exist on the request object now you can use the has property to check to see if a specific cookie exists or delete a specific cookie as I mentioned you can also set cookies on the response object to set cookies on the response object you'll create a new response by calling the next response and next this is going to get you the response object you can then use the cookies property on it to set a specific cookie like bypassing key value pairs or by passing in an object that has a name value or path and path for that specific cookie and then you would return this same response that you created by getting uh by calling the next function on an X response now similar to cookies you can also work with the headers you can set a specific header on the incoming request you can clone the current headers of your request and then set a new header on the request object you can also use that to set a new response header on the response object you're actually returning from this middleware so it's just like Express Middle where it receives a request and it works on it you can set headers on it or you can generate or produce a response and then send a response here if you're actually also setting a header on the response object before returning it to the user okay now let's jump into the code and see this in action now going back to our project I've included this middleware.js file inside of our The Roots directory of our application so therefore we can play around with this middle verb now the first thing that I want to show is accessing this next URL object on the request object which is a parsed object from Nexus specific URLs so we can read stuff like the path name or the search parameters that the user is actually passing to our application or from the incoming request and then responding so I'm using the next response calling the next on it which is going to return this response back but I'm actually reading the path name and the search parameters and down here I'm matching this middle virtual only run if the request is coming for forward slash about page so if I go to the application let me just open up the terminal so we can actually see this console log that I'm doing here from the path name so if I go to the application and go to forward slash about to match this specific uh middleware this is going to run and as you can see here I have this object locked to the console that has a path name which is four slash about and then this sort is setting to null now what I'm doing with the sort is that this search parameters is the search parameters or the query strings on the corner URL this is a an instance of URL search parameters so you can call the get property on it to actually read a specific value from this search parameters object now I don't have any query strings there that's why it showed null but if I go ahead and actually include a sort Curry string if you can see it up there it's a little small but down here in the console you can see now I have this path name and the sort property on the URL search parameters set to this value of ascending that I've passed in to my URL so that's the first example of actually working with the request object which is an instance of the next request object which is itself an extension of the web request API specifically this next URL exists on this next response instance now the next example is actually redirecting so let's say if somebody is trying to access the about page I want to redirect them to for slash team so I'm using the request URL which gives me the base and I'm using this new URL to construct a new URL and append this path to that base and then redirect the user to there so I'm just save this if I go to the home page now if I try to access the forward slash about it should redirect me to the team so I'm up there on the team and here you can see I'm on the team page so easy as that you can just redirect you can also rewrite so it's the same way so if I now go to the about page as you can see here up there still shows about but it's taking me to the team page um so rewrite is proxying you to rewriting the URL to a different URL while actually it's preserving that same path that the user was trying to access in the beginning now the next example is just to read all the cookies there is no cookies set for us but if you were to read the cookies you could just get all the cookies this is going to get you an array of objects of the current cookies on the request object but down here we're going to actually set some cookies so let me just comment this out um now what I'm doing here is I'm creating this response object out of this next response this allows me to set some cookies I'm passing in a cookie with the name of next value of fast and on the home page as the path and then I'm returning the response let me just comment this config matcher out so it runs for all the requests on our page now if I go to my home page and actually open up our inspector here to go to our net to go to our application on the cookies you can see this next fastest set on this path so we were able to set a cookie on the response objects we returned from our middleware now the next example is to return some Json data blackhead API so let's say I want to match only if a request is coming for the API route let's call it test and if this is a path the user is trying to access I just want to respond a Json data that has an object or this object that has a message with the actual message of hello from middleware now if I go to my home page and refresh if I try to access the API for slash test I'm going to get this Json response with the message that I provided so you can see from your middleware you can return Pages you can rewrite redirect you can even respond with a Json you can access the cookies you can modify cookies or headers and more that's enough for this video folks we talked about next year's middle verse which allow you to intercept the request and execute some code before the crew request is completed if you have any questions hit me up in the comments if you're interested in learning Nexus 13 my course was just published today after months of rewriting the content and battling with the new next.js updates every weekend every month so definitely check it out if you have any questions let me know and hopefully I'll see you on the other side bye
Info
Channel: Hamed Bahram
Views: 19,436
Rating: undefined out of 5
Keywords:
Id: NUHAc1wjL3A
Channel Id: undefined
Length: 17min 26sec (1046 seconds)
Published: Sat Jul 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.