ExpressJS Tutorial #5 - Cookies

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
alright guys so we're back with a brand new video so we're gonna talk about HTTP cookies so what exactly are cookies well they're just a small piece of data that is sent back from a server to the client the client can be either the web browser in our case we're using postman so postman is our client so postman will actually store the cookies if the web server sends one back to us and it basically allows us to make subsequent requests to the server to exchange the cookie for a piece of information and that piece of information can be a bunch of different things that can be our recent orders that we had placed it can be our credentials it can be the items in our shopping cart a whole bunch of things remember cookies allow us to keep track of the state of our HTTP requests because by default HTTP is stateless it's independent every single request made is independent from the other one so in order for us to keep track of requests so for example activity from a user maintaining logged in users keeping track of items in a user's shopping cart we need to use cookies now typically there's also a local storage they can use these are just some examples of perfect use cases for cookies so let's talk a little bit about how they work at a high level and then we're gonna go ahead and implement it in Express so think of it like this the user enters their username and password they click on the login button ok now a request is made to the server and basically we make it post requests to the server passing in the username and password in the request body and the server what it will do is will generate a unique session ID for the client now the server is gonna send back response attaching the session ID in the headers so that way when the browser has the cookie it stores it every single request that is made to the server will send that HTTP cookie to the request header now the correlation between the session ID and the cookie is simple the server generates the session ID and you can actually use a session ID on the browser as a cookie ok every single time you make a request to the server with that session ID with that cookie it's basically going to uniquely identify which user which session that made this request so we know who is making this request and yeah so once the request is made the server is gonna receive the request the middleware functions will take care of parsing the cookie receive and then on the server side we can also check which user this cookie belongs to and then we can for example check database see what session ID this correlates to and then now we know which user it is so we can perform whatever business logic we need for that user all right so let's pull what we just learned into practice so we're gonna go ahead and send a cookie back to the client but before we do anything else we need to install something called cookie parser so this is going to be middleware function that we're going to import right up top over here so constant cookie parser equals require cookie person I should probably put this right up top over here okay so because by default Express will not parse cookies for us so we need to use cookie parser so that way the request object so if you go over here if I type rect cookies you can see that there is a property called cookies but it's going to be undefined okay so we need to use cookie parser in order for this metal work function to be registered in our app that way it will parse the cookies adora if there are that way it'll parse cookies if there aren't any so we're going to call app dot use D parser there you go we just invoke the function just like that and you can also pass in a secret as well but we're not going to worry about that before for now okay so what we're gonna do is let me make a simple route we're gonna use a new route so well first to app dot gets let's just pretend we're signing in okay because quite often whenever you are logging into website it's going to send you cookie back all right so let's just simply do this let's say our res not cookie so we're calling the cookie this is a function on the response object okay we're not calling we're not doing rec cookie because the request object you don't set cookies on the request object you said on the response object so now the cookie just needs the name so we can call us whatever you want so I can just say let's just say session ID and let's give the session ID of one two three four five six okay and let's go ahead and send a response back and let's just send we can also send Jason like this so I can do something like message logged in all right so now we're gonna go into postman and we're going to make a call we're gonna make a get request to localhost port 3000 at the route signed it so we're just basically pretending like we're signing in so we're going to click on send of a pay attention to a response order seizes okay and notice how there's this cookie and notice how this session ID 1 2 3 4 5 6 so we have this cookie that lives on the client side now the browser or this another browser misses our client postman so now what we want to do with this cookie is every single time a user makes a request we want to validate the cookie we want to make sure the cookie actually exists so what I'll do is I'll write a middleware function so we're going to kind of bring together in the previous episode with this episode we're applying our middleware knowledge with this episode so let's do this let's create a function validate some cookie and it's going to take in our three parameters request response and then next which is a function to be invoked so we're gonna do this let's get the cookie so const cookies so we're destructuring cookies okay and what i want to do is first let me actually console.log cookies and i'll just call next show you guys how it looks like and we're going to mount this middle function to this sign-in route okay and typically a sign-in route should be a post request so let's click send and you're gonna see that we actually have an error and it says cannot send the headers after their sensitive clients you know why it's because we did that said it should be dot status sorry about that okay let's send it again okay there we go logged in okay and you can see right over here we have this object that's the cookies object request cookies you can see the session ID so what we want to do is you want to validate that cookies object right you want to make sure that cookies has this session ID okay so we can say something like if session ID is in cookies so if that's true let's just say console.log session ID exists okay so that basically means that the client sent a cookie to the server okay but what we need to also do is we need to make sure that this cookie is actually valid because if it's not valid and if you actually allow the user to use his cookie that can be very crucial that's a vulnerability which means that they could just change their cookies to whatever they want and they could basically act as if they're someone else and you don't want that but you always want to make sure you're validating your cookies okay so let's simply just do this let's just say if cookies that session ID is equal to one two three four five six because that's what we said as of here let's call next okay now else if it's not equal and what we'll do is we'll just say res duck status four three send message authenticated okay and we'll do the same right over let's see right over here let me get rid of these curly braces because we don't really need them alright so now what we're gonna do is we're just gonna go to sign-in okay so it should say logged in so now watch this if I try to ok so obviously doesn't really do anything cuz we're saying the cookie over here well let's do this let's visit another routes let's do a plot gets let's just pretend we are visiting a protected route so let's just say protected and we're going to validate the cookie okay so our middle-earth function is going to be called it's going to check if session IDs inside cookies if it is it's going to validate the cookie itself and if that's validated if it's correct it's going to call the next function we're just going to invoke this callback function over here so we're just gonna save as dot status 200 Chasen okay so this should work if I were to go to protected you're authorized and that's because we have this cookie the session ID okay now let me go ahead and delete this cookie now and watch this see how it says not authenticated because we don't have the cookie essentially we destroy the cookie on the browser so when we made the request the cookie the session ID was not present okay but we can always visit sign-in and you can see that right over here it's saying not authentic in but let's actually fix that real quick let's actually get rid this middleware because when we sign-in we should get a cookie so let's go here so logged in so now you can see I have a cookie so if I go back to protected it's going to say you are authenticated okay so this might be a little confusing because you're probably wondering well what exactly does this really mean so think of like this right whenever you log in it's going to send back a cookie and that cookie is going to be the unique ID that we talked about earlier in the previous slides that's the server is going to generate now here's the thing we are hard-coding a session ID you do not do that in a real application what you want to do is you want to generate a unique session ID and that session ID is going to be saved on the server and every single time you make a request through the application you're going to check to see if that session ID is valid because if you just have easily guessable session IDs anyone can just send these cookies to your server and it's basically as if they're logging in to your account and you definitely do not want that to happen so when we send the cookie back we now have a cookie stored on our client okay and we can use this cookie to send it back to the server to access protected routes like this one right over here this route is going to always call this validate cookie middleware and it's going to make sure that the cookie is correct and if I change this condition let's say if our session ID is different if I try to visit this again it's going to say not authenticated that's pretty much it for this video and I'll see you guys in my next one peace
Info
Channel: Anson the Developer
Views: 13,250
Rating: 4.9640718 out of 5
Keywords: discordjs, discordjs v12, discordjs version 12, discordjs tutorial, discordjs v12 tutorial, discord bot, how to make a discord bot, how to build a discord bot, how to code, discordjs tutorial series, javascript tutorial, how to code in javascript, async, await, python, discord roles, discord add roles, discord bot add roles to user, how to add discord role, discord embed message, command handler, full stack development, web dev, html, css, javascript, js, deno, typescript
Id: 2so3hh8n-3w
Channel Id: undefined
Length: 11min 4sec (664 seconds)
Published: Sat Jun 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.