Cookies in NextJS: Easy To Learn & Super Useful!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
cookies can be really useful in doing a bunch of stuff for example a verifying front-end requests or doing a lot of stuff they have so many use cases and today we're going to cover how to work with them in next JS first we're going to take a look at how middleware Works in next shares and how do you define it and how do you specify when it runs and then in the Second Step we're going to take a closer look at how to work with cookies and headers in nexjs middleware I think understanding The Core Concepts of middleware so cookies and headers are really beneficial for your future projects and understanding extra s and so let's get right into it okay here we are in an xjs project and now to get started with the middleware we're gonna want to initialize a new file and call it middleware dot DS so that's quite straightforward and what you really need to pay attention to is that this middleware file is at the same level as or Pages or in this case in Nexus 13 the app directory and only then will the middleware work now from this middleware we're going to export a function let's call it middleware but you can I think you can call it whatever you want it's going to take a request that is going to be a next request we're gonna get that from the next server this type and then let's just return a next response which we also get from the next server dot next now if we log to the console middleware ran and I think this server is already started yes it is um so let's head over to the server reload the page and see what happens in the console oh by the way I can make the code a bit larger for you okay so if you look into the console as we can see the middleware ran a bunch of times why did it do that well we can take a look at that so if we log out the request and then say request dot next URL dot path name log that out for every request we can actually we can just remove this save that and when we reload the page we should be able to see all the paths that you know Nexus has requested and this is very interesting so it's the home page because that's what we loaded in the browser but the home page also needs a bunch of files so that would be the CSS the webpack.js mainapp.js then also the little icon that is at the top and we can see all files that are being requested in the middleware because at the moment this runs for every single requested item now if we want to limit that I've got the documentation over here on the left if you want to limit that we can export export a constant and call it config and that is going to be equal to an object and now in here we can Define the matcher the matcher and it's pretty much just going to be a string and this cannot be dynamic so it can't be generated at request time or whatever this will be done at build time so that's why this match will be just a regular string and for example we can say slash so that means only the home page so whenever this is true then the middleware will run and this is only true well for one of the base paths that we have seen the one right here and that's why the request um like the middleware only runs for the home page now we wouldn't really have to say this we could also do something similar we could say if request.nexturl dot pathname dot starts with and then we could say something like slash and if the path name starts with Slash we're going to return the next response to next and we're going to log out middleware run and get rid of this for a second now it's quite interesting what you're gonna see now so if we read out the page you're going to be able to see okay so the middleware run a bunch of times again and that is because as you remember the past the the path names all started with a slash right we have slash favricon we have slash underscore next static and for those three and then we have just the basic homepage that also starts with the Slash and that's why it runs five times because we're not really limiting anything with the statement but it still works so you could use that instead of the Metro if it suits your use case and while there's a lot to be said about the logic that we can use in Middle words that's not really what we're gonna get into in this video we are going to focus on working with cookies and that's why I've got Chrome open here because I am thoroughly convinced that Chrome just makes working with cookies way more enjoyable than something like Firefox and okay so how do we work with cookies so let's return the next response next again start next so that just means oops and we need the response there we go and that just means okay do whatever you actually intended to do so we are intercepting the request in the middleware and then saying okay you can just go on and do whatever you set out to do if we want to get a cookie in the Nexus middleware we can say cons uh cookie is equal is equal to and then we can say request dot cookies dot get so as you can see this right here um is something like a map when we hover over it we can see it's of type next cookies we can say dot and then like entries for each like for each cookie that we have has and keys there's a bunch of cool stuff we can use and we're gonna say get and we are gonna get um a cookie called oth now that off cookie um probably doesn't exist right so where would that come from let's say cookie and then log out the cookie and when we reload the page like this let's take a look at what happens in the browser console so cookie is undefined interesting and now in this case I do want the mattress so as export cons config is equal to an object then inside this object we're going to have the matcher which is equal to the home page because that is the only time we want this middleware to run so in this case it should log out you know cookie undefined once and that's what it does okay now let's go into Chrome and actually set that cookie so we can go to application and if you didn't notice you can see all the cookies a website uses if you go to the Chrome Dev tools and then under cookies you could see every cookie and in this instance we can see there are no cookies so let's set one let's say the auth cookie and it has a value of one so we are auth pretty much in this case we are not checking for the value we're just checking if the cookie exists or so technically if we read out the page right now and the Earth cookies here and now in the console it will log out the value of the cookie and this is an instance where the documentation of nexgs is actually a bit wrong because in the documentation I've got it open here on my left um the way they got the cookie is by doing this so they're saying conscope is equal to request.cookies.get.nextgs.value and we can change this to rec and as we can see this value doesn't exist so if we change this to auth we could change this to Value off and see what happens because well we can't use value it doesn't exist let's see what it logs out and now it logs out the value okay so we could either use this right here this syntax and that should return the one if we read out the page or we could use the dot value off and invoke that and that will log out exactly the same thing so it doesn't really matter what you do as long as you don't follow the actual lectures documentation because that won't work okay now that we've got the cookie we can do something with a cookie um or we could get all cookies let's take a look at how to get all cookies so if we say counts all cookies is equal to request.cookies and then in the documentation they do get all which doesn't exist and I find that to be very confusing um so what I I figured out is that we can just say all cookies is equal to request.cookies and then if we log out all cookies as you can see that will work just fine so let's reload the page and take a look at all cookies we can see it's an object that has the auth and auth is equal to one at the path of the home page so exactly what we want pretty much now we can take a look at what functions we could do we could say you know values we can try that I don't think that will work though we can read out the page as see where it logs out and it just logs out an empty object so that won't work but request.cookies just you know it works just fine now if we wanted to check for a particular cookie for so in in our instance that would be the auth cookie we can also do that so we can say um const is off is equal to them or actually know let's let's not do that just so you can see it a bit better I'm going to log it out to the console so is off and then we're gonna say request dot cookies Dot and then we can see um all the functions we can use and in this case we're going to use the has so we're going to check is this cookie existed so let's do auth and as we can see right now when we reload the page in this console we can see is auth is true that means the cookie is existing now it does not um say anything about the value so the value could be empty and if we reload the page it would still say is all through just because the cookie actually exists so be careful when using this it just um looks into the cookies and sees does it exist now if we see that it has the cookie we can also delete it so we can say and before the is auth is even when react dot cookies dot delete and then we can delete the auth from that cookies and see what happens so reload the page and now the is all this false because originally the cookie existed but we are really like deleting and removing it and then logging out does it exist and obviously after deleting it no it doesn't exist anymore so reloading the page um no it doesn't exist yet in the browser it still does exist so we're not actually deleting the cookie from the browser we can reload this and as you can see the cookie still persists now working with cookies and getting them is all fun and games but we are we also want to work with them so we can say a next response and the response is the argument we get is the second parameter of the middleware function and now we can say something like response dot cookies and now we also have a bunch of options and we could say like set and then we're going to set a new cookie that says you know m is or uh two and then we're gonna set the value of that let's just have a string that says true and now we can set out and we can log out the um response say response dot cookies save that and reload the browser page and let's see what happens um oh cannot read properties of undefined reading set okay that is interesting um so why is that happening okay because we can't set the actual response we do need to say something like this so let's define the response as the next response dot next and now we can say response dot cookies dot set and we are gonna set is our is off two we're gonna set that to a string of true we can remove this from the arguments we don't need that anymore and then let's log out the response and say response dot cookies no okay let's see what happens we're gonna read out the page and no let's take a look at the browser and is auth is auth 2 is equal to true so exactly what we want and now instead of returning next response.next we can just return the response and that will you know include the headers we set on that resp um not the headers the cookies we set on that response okay and the reason I said headers um accidentally instead of cookies is because we can also set headers so we can say for example the next response of next is equal to the response but then in here we can pass an object and that object can have a bunch of properties of status text status requests and headers in the order instance we are going to worry about the request because we're going to modify the request headers in next.js which is not really hard to do so this takes a headers and that headers is going to be the original request headers so that could just be wreck dot headers or you could also say um new headers inside of here we can pass the request dot headers so you know that also works and below this response we can now do something like response dot headers dots and again we have a bunch of options we can have here we can say for each header we can say log out the header and say header let's see what happens let's reload the browser page open the console and okay wow that's a bunch of headers so we have the max age we have the keep alive the auth we can just see every header that is in or responds now if we wanted to modify it we wouldn't you know just log them out we would say response dot headers and then we can set or custom header so we can say something like X custom auth header and let's set that value to you know is auth or whatever you want to set it to pretty much we can save that and then because we are returning this exact response and not something like nextresponse dot next which wouldn't work because of that we can see that our headers will get passed so we need to return this response and now before sending out that response we can say console log oops console log a response headers and in here we could say response dot headers and here we should be able to see our custom header that we have just set so we can refresh we can see is auth2 and auth in our browser console and here we can see all of our headers now we don't care about many of these but we can worry about one of them that is down here so X custom auth header is off and you know you can work with that on the server side or wherever you want to work with the header um yeah that can be really useful just setting them here in the middleware and that is pretty much all there is to working with headers and cookies I'm going to link the original documentation and further reading if you want to get more into the topic but those are the basics and I think those will cover like 95 percent of the use cases so for example when working in a real production application you could um check if user has a cookie a certain one and if they don't then you assign them a user ID so that is a common use case for me personally um let's just get rid of this error for a second um if they don't have a cookie you assign them a random user ID by generating one with an npm package and if they already do then and we can just forward the request and I think that would be just one of the most common use cases so every user gets a cookie that has a custom user ID that you can use to you know just verify for example front end request from so for instance I remember the startup we built together on this YouTube channel there is a demo and whenever you go into the application settings you can see that each user has a user token that we send along when making a request to the artificial intelligence that powers this application that doesn't work at the moment but you know just like the the AI itself doesn't work at the moment the user token does so yeah that would be one common use case you could use nexgs middleware for okay that's pretty much it I really hope you enjoyed this video thank you for watching and I'll see you in the next one bye
Info
Channel: Josh tried coding
Views: 11,417
Rating: undefined out of 5
Keywords: nextjs, middleware, cookies, nextjs cookie, nextjs middleware cookie, nextjs tutorial, josh tried coding, joshtriedcoding
Id: vsEKmufzT6M
Channel Id: undefined
Length: 16min 50sec (1010 seconds)
Published: Thu Nov 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.