Your complete guide to understanding the express-session library

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video is part of the passport Jas user authentication series and it's kind of a follow-up discussion to my video on HTTP headers and cookies so I'll leave a link to the series playlist below and that other video which should be just before this it can also be used as a standalone lesson if you just want to know a little bit more about how Express sessions or sessions in general work so in this case we're gonna be looking at a very simple Express app and I'm gonna take you through how the session is working how the cookies kind of work with the session and some of the configuration that you have to do to set up the Express session middleware what I've got open right now is the repository that goes along with this passport j/s tutorial series and we just have a folder for little one-off tutorials like this one I've already created an application which is an Express application and I'm just gonna quickly walk you through what I've done and then we'll go through what's actually happening what are some of these configuration options so the first thing that I've done I've already installed my dependencies we've got Express Mongoose for the database and then Express session which is an NPM module we then have something called connect which we'll get to in a few minutes it's what we're gonna actually use for the session store but then of course we set up our Express app pretty familiar to most people we connect to our database right here so I'm just using a completely unauthenticated local host database I've got that running in the background already so if you're trying to follow along be sure that you get the DB server or that process running before you try to run this app so we're just going to use the tutorial database and then these options here are just set because when you run the application is going to complain about it if you don't put these so that is all we've got and we create the connection right here so the connection represents our database connection and then down here we have some pretty familiar JSON and URL encoded middleware which is going to allow the Express server to parse the different request types so that just pertains to the type of responses that we're getting in on the server and then finally we have things related to the session itself which we're going to dive in a little bit deeper and at the bottom we've just got we're listening on localhost 3000 and we have one simple route for the home page just says hello world sessions so that is our app this is the only file we're working with and so it should be pretty straightforward like I said this tutorial is not an Express tutorial and I assume that you already have a decent understanding of how the Express framework works I'm trying to stick primarily to how the Express session middleware works so if you don't understand how Express works or how middleware works be sure to check out some of my other videos or just read some of the documentation online before we get into any of the configuration and understanding how the Express session works we need to answer the question what is the difference between a session and a cookie you'll see that in the configuration I've got a cookie set and in a previous video that I did again link is in the description we talked about what a cookie was so basically a session in a cookie are different in the places that their data is stored so a cookie has its data stored in the browser and that browser is going to attach that cookie key value pair to every HTTP request that it does a session on the other hand is going to be stored on the server side so when I say server side just the Express jazz application and so this Express session is going to store a little bit bigger types of data so in a cookie you can't put a whole lot of data and it gets very tedious if we're constantly adding more and more data to the cookie that we're attaching to each request so it would make sense to put that in a server side session where we can store much larger amounts of data in addition a server side session is advantageous because with a cookie we cannot store any sort of user credentials or secret information if we did that then a hacker could easily get ahold of that information and steal personal data so the benefit of a session is basically the fact that we have it on our server side and we're actually authenticating into the session with a secret key so with that said that is the main difference between a cookie and a session and I want you to keep that in mind as we're talking about the two in this video now that that's covered we have some time to get into the actual code in configuration of an express session and then I'm going to show you kind of how it works in real time so what we've got on the screen right now is the Express session documentation it's just an NPM module a pretty popular one at that and you can see on NPM J Escom there's all the documentation that you would need to learn how to use this but I'll just point you towards a few of the common things that you'll see first off of course we require in the Express session and then these options right here are what are going to be included in that options object so if you look at the code here you'll see that for our session we're saying app dot use so that's just we want to use the session middleware and then we've passed into the session middleware an object right which represents our options so if we go back to the documentation really quickly you'll see that all of these options are documented right here under the options section now the one thing that I wanted to point out you get through the options that's great fine but then you get to the bottom somewhere down here and it talks about a session store implementation so if you're unfamiliar with what that is it's basically deciding what persistent memory are we going to store our sessions in if you remember from a few minutes ago I said that a session is used to store information about a particular user moving throughout the browser or a client and so we can potentially get up to a decent amount of information and therefore in a production environment it would be useful to have an actual database storing that information now by default the express session middleware just comes with its own implementation of a session store but it's not using a database it's just using in memory or memory that's local to your application and it's not going to be a scaleable solution so what we need to do is set up an actual session store which is a fancy way of saying we need to connect our database to the express session middleware so there's going to be a lot of options for what session stores we can use and they're documented here at the bottom the one that we're using particularly is the connect session store which is probably one of the most popular ones and it allows us right here to connect to the MongoDB database that we have running in our Express app so let's go back to our app real quick and see what I mean so to do this session store to connect it up we first have to have our database connection so we talked about this a few minutes ago here's our connection we're just using a tutorial database on localhost nothing you know you'd obviously want to change this if you're in production but we've got this running on my computer and I can actually come down to the terminal here and run the shell and you'll see that we can show DBS and you'll see that we have a tutorial DB setup when we connect it to this database now what we want to do is we want to tell the Express session middleware that we want to use that DB database for its session store so you'll see that that happens right here in the store option of the session middleware and so what we've done is we've passed in the session store object into this store option and the session store object is set up right here and it is basically just using that connect right here the connect package and we're configuring a few options we're saying that the connection equals the connection that we just set up and the collection that we'll be putting our sessions in is going to be called sessions pretty standard a pretty standard option that we have here you can obviously customize it a little bit and if you went to the documentation of Connect there's a few other options that you can set but what I want to show you is what is happening when we connect everything up so in my first terminal I will run this application so let me go to the path here and we're gonna run the application so we are listening on localhost 3000 and if we come into the browser here I've got this queued up so that we currently have localhost 3000 ready to go but I have not clicked refresh yet the reason being is because I want to show you exactly what this middleware the session middleware is doing so let's first come back to our code and what we want to do is go to the shell and that we want to use the tutorial database so now we've switched to the tutorial database let me clear the screen and we're going to show the collections that exist in that database when I ran the app it initialized this sessions collection in my database but if I say DB dot sessions that find there's going to only be a couple objects in here let me just go ahead and drop this really quick because I think I had some stuff from previously so let's just say DV dot sessions dot drop so we drop to the database we show the collections now there's nothing but if we were to come here and refresh the app so we're using node mons so if we click Save it's gonna refresh the app we're gonna go into show collections and you see again that the sessions have been established and if we say DB dot sessions that find we shouldn't find any documents whatsoever in this collection so we have a completely clean slate and in order to establish a new session all we have to do is make some sort of HTTP request to our application so if I came to the browser and I clicked refresh here what's going to happen is that session middleware is going to kind of fire it's going to create a session and then what it's going to do is create a session ID which is going to be stored in a cookie in this browser so like you know just like we don't have any sessions in the database yet we also don't have any cookies in the browser yet so let's go back to our code and what I'm going to do is just walk you through a few of the options and then we'll finally see exactly it's working so when we set up our session middleware we have a secret pretty self-explanatory but this secret is going to well usually it's going to be stored in an environment variable and you don't want to expose this to the public because it basically says if the secret is invalid then the session is invalid too but in this case I just put some secret just so that we can have it all in front of us then we have a couple options here resave and save uninitialized and these are just options relating to what does the session do if nothing has changed what does the session do you know if something has changed and basically tells the middleware how to react to different events in the browser you can read up on the documentation a little bit more on these options but the thing that we're interested in we already talked about the session store but what we're doing is we're setting a cookie max-age so in other words like we talked about in a previous video a cookie can have an expires header and are not a header but an expires property which says after a certain amount of time the browser's going to delete the cookie and it's not going to attach to any of the requests in the future so in this case we're sending our cookie equal to one day and you can see the math that we're doing here in the comment we're basically just saying one day 24 hours in a day 60 minutes in an hour 60 seconds in a minute in a thousand milliseconds in a second and so that's the math that we're doing right here to get to a full day for that expires property so basically what's going to happen when I send an HTTP GET request to our sole route right here is the session middleware is going to initialize a session and then it's going to take that session ID and set it equal to this or set the cookie equal to that session ID the cookie is then going to be put in the set cookie at HTTP header and then that is going to be in the response header it's gonna go in the browser the browser is gonna receive it and say oh you want me to set this cookie I'll set the cookie and now every time we refresh that cookie will be a part of that request so let's go ahead and do this we're going to visit our only route in the application and to do that we need to go to Google Chrome and we're gonna click refresh so when we clicked well now we it did not load so let me go ahead and do that one more time we refreshed it we get our response it says hello world sessions and what you'll notice is now we have this cookie which is by default called connect dot s ID in the express session middleware and we have some sort of value here which somehow corresponds to our session ID so basically what's happening is the Express session middleware is going to get this cookie on every request it's going to take the value of that cookie it's going to say ok look up this session ID in the session store which is the database and then it's going to say is the session valid if so let's use the information from the session to either authenticate our user find out some data about our user may be like how many times that user has visited our site anything of that sort is what's going to happen when the user loads a different route you'll also see that we have an expires property right here that says tomorrow this cookie is going to delete from the browser but for now since so it's still valid it's going to attach to every single request so if we go to the network and look at that last request we'll see that in the response header this came from our Express server using the Express session middleware we have the set cookie header and we set the connect dot s ID header and we gave it an expires now in the request headers since we only did this once you won't see any cookie but if I click refresh one more time and we look at the request headers in response headers you'll see that in the request headers we have the cookie that was set previously so in other words the browser is saying okay I have a cookie that is still valid let me attach it to every quest within this localhost domain alright so we have this cookie on every request now let's see what's happening on the backend so let's go back to our code and we are in the shell so we're looking at our database right now and we're gonna type in dB well let me clear this real quick DB dot sessions dot fine and that's going to look in the sessions collection for any documents in that collection and you'll see that we have one and only one document which represents the session that we just established in the browser so you'll see that the ID is right here which you can also see in that cookie that we have in the browser so let's see the first couple letters were capital a y Y J so let's go back to the browser and you'll see that the cookie right here is has got that ID set in it so that's how we kind of connect the back end to the front end and then in let's once again come back to our code so we also have the expires header within here so we can also validate it on the back end and basically what this is going to do is every time the server gets that specific cookie with that session ID attached to it it's going to come to this sessions collection in the database it's gonna grab that document out of the database or the session store and it's going to get information that we have set onto that session use it to do whatever we want to do with our application now this is great and all but what do we actually use this express session middleware for well in another video in this passport j/s series you'll see how passport j/s actually connects in to the Express session middleware and uses the session to actually authenticate the user but since this is kind of a standalone video I'm not going to get into that all I'm going to show you before we kind of conclude is where this session is being set now we know that the cookie in the browser has the session ID and we use that session ID to look up the session in the database or the session store now we can also come to our routes and get information about the session so if we said console dot log request dot session you'll get to see exactly what that session looks like and we can actually set properties to that session so again I'm connected using node mon-sol will automatically refresh when we save this app so let me click ctrl s to save you'll see that something happens here so we reset and now if we visit this route again in the browser in the console we should see the session object so let's quickly switch over to the browser will refresh refresh this page and then we'll come back to our code window and you'll see that our session object has been printed to the console right now all we have is a expires header and a couple other metadata properties but what we could also and this is set to the cookie object but we could also set other information so we could set something like how many visits a user has made to our page so let's go ahead and do something really simple like that in our only route that we have for this application let's just say if request that session dot view count we want to say request dot session dot view count equals request that session dot view count plus one or you could just do the plus plus syntax at the end you could just do something like that and be done with it but we'll be really explicit here and we'll set a value okay so if we have that property on the session we're going to increment it by 1 and then what we're gonna do is we're gonna say in the response instead of hello world we're gonna say you have visited this page X amount of time so we'll use a little JavaScript syntax and we need to change these two back ticks so get this to work and let's see we can just put in requests that session dot view count and now it should tell us how many times we visited this page when we visit that page now we also have to say else because in this first occurrence we're not going to have this property set so if that does not exist then we're going to say request that session that view count equals one all right so we have set a property to the session object and let's go ahead and save this application and go to the browser and visit it so we're in the browser now and we will reload and it says you have visited this page one times it should be time but now every time we refresh we're going to get that number to increment because of the logic that we've put into our route so you can see how this session object could be very useful for tracking information about a specific use or client one last thing I want to show you if we go back to the code you can look it up in the database again so let's go back to and let's find that session once more you'll see we still have just one object one document in the database but now we have this little property down here so when we set the view count property on the request that session object that actually persisted in the session store or our MongoDB database under the view count property so again you can see how powerful this is and you could also kind of extrapolate out and start to foreshadow how something like a passport j/s middleware could kind of connect into this middle this express session middleware to keep its own sort of data that's it for this video be sure to LIKE and subscribe if you are continuing on with the passport j/s authentication series I think this may be one of the last kind of filler videos before we get into the actual configuration of the passport middleware so be sure to check out if you don't know where that is the playlist is listed in the description otherwise I hope you learn something from this and have a good one
Info
Channel: Zach Gollwitzer
Views: 35,460
Rating: 4.9733868 out of 5
Keywords: passportjs, user authentication, nodejs user authentication, expressjs user authentication, passport local, passport jwt, javascript, express middleware, HTTP Cookies, HTTP Headers, express sessions
Id: J1qXK66k1y4
Channel Id: undefined
Length: 25min 50sec (1550 seconds)
Published: Mon Jan 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.