Express JS #18 - Session Stores

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay so now let's go ahead and move on to session stores so this is something that you very likely will need especially when you want to persist session data for the user because sometimes your server may go down for unknown reasons and they might restart and when that happens all of your session data will be gone because by default Express session stores it in memory so what you want to do is you want to store this in a database so that way it can be persisted whenever your server Goes Down And if it go goes back up the session store will have that session data there and express session will look in that session store in the database to grab the session data and restore it for the user so earlier I actually did show you how the inmemory session store looks like and how it stores data I'll show you again so inside my API users endpoint is where I have this being uh logged so what this does is it looks for the session ID and uh if there are any errors I'll just throw an error but then we pretty much just log the session data right over here so right now I'm not logged into the application at all I'm not authenticated so I don't have a cookie or anything but if I make a request to API users and if I show you the logs you can see that right over here uh inside session store get that's where I'm logging this right over here you can see that the session data is undefined okay that's fine let me go ahead and log in first cuz we haven't actually U modified the session data at all we haven't actually logged in yet so let me go ahead and log in so let's do this API SLO log in oh whoops did I forget yep sorry about that uh bad credentials uh oh wait you know what it is it's because I'm still comparing the old the raw based the raw text password and database let me use uh Johnny instead and then the password is I think it was hello 1 2 3 as well okay so I just successfully logged in let's verify let's go to the status endpoint and you can see that I'm logged in obviously you don't want to return the password but that's something for a separate part of this tutorial but now watch this when I go to/ API users you can see that in the console so we're inside session store get so we're logging it right over here and then you can see that this is the session data and you see how the session data I have the cookie and then I have the passport and then I have the user okay so every single time we make a request to the server um Express session will take care of looking for the session data in the inmemory store and then it will know who the user is okay and then right over here we have the user ID uh inside passport okay and then passport will take care of calling the serialized user with the ID and then it will search for the user in dat database and then that's how it'll grab that user from the database and attach it to the request object okay so if the server goes down so let's say right now if I restart the server and if I try to visit uh let's say if I visit the previous endpoint let's do au/ status you see how it says unauthorized so we're not even logged in anymore okay all of our session data is gone if I were to go back to SL API users you can see that now the session store does not have our data it says undefined so obviously that's a problem so what we can do is we can use a session store to save the session data and it's actually not that difficult to use because all really need to do is just have a database connection which we already do already so in earlier parts of the tutorial I showed you how to connect to a mongodb database using so that's this right over here and then what we can do is we can reuse that connection to connect our session store to that database so we're going to use this package called connect and pretty much this is just a mongod DB session store for Express now let's say for example if you're using some other database there are a bunch of different session stores right over here so this is the express session documentation if you just scroll all the way down and you scroll down to compatible session stores you can see that let's see there is one for couch base DB there's one for uh mcash yep connect over here there's one for SQL this is the Microsoft SQL Server neo4j redis Firebase there are a bunch okay so you just have to look for this look in this list and find the one that you want to use we're just going to use connect for now so let's just first install connect so inside my terminal I'll type npmi connect and of course you must make sure you have already a database connection so in this case since we're using I can actually just reuse this database connection so now that we've installed connect we can import that into our index file so I'll import store from connect just like that and then we need to go down into our session middleware and we need to set this store property so where you're pretty much calling this session function and then you want to reference store. create and since we are using we can actually reuse that connection so there's this property called client in the connect options like this and then you can reference which which we have imported up top over here and then you can reference connection and then you can call this gets client method just like that okay and this says Returns the mongod DB driver Mong client instance that this connection uses to talk mongod DB okay so let's go ahead and start up the server again and let's just make sure everything is good okay so we're connected to the database and let's actually try to authenticate now because that's what actually modifies the session so let's go ahead and make an API request to API let's send the username Johnny and then password hello1 123 so we are logged in successfully no errors in the console okay that's good now let's go into our database and let's see what happens okay so I'm going to refresh and you notice how now there is this sessions collection okay notice how now there's a sessions collection let me expand this real quick and you can kind of see how we have uh let me see if I can kind of do this so we can see it better okay so you see how we have this sessions collection R of here so now we're actually storing the session data in mongod DB in our database so then what happens is now I'm logged in okay I just logged in I'm going to make a get request to the o/ status endpoint to verify that I am logged in which I am okay so we're good now watch this the problem that I mentioned earlier was that if I were to close the server so I'm going to exit the server and if I restart it it would log us out because all of the session data was saved in memory but because now that we actually have a session store that is a database it will use the database to restore the session data so watch this okay so I have my session data stored in the database and notice how if I make a get request to the o/ status endpoint notice how I am still logged in okay if I remove this store completely it's going to use the memory store by default okay and let's go ahead and restart the server click send notice how now I am unauthorized because my session data is not found in memory because it's using the in stored by default so I I really hope this makes sense and I I hope this showcases how important a session store is because now instead of having your session data stored on stored in memory it stores it in a database which is great for persistence okay so you can restart your server how many times as you want the session data will always be restored so notice how now if I just call this endpoint again after just uncommenting out this part the store options now we see our data so what happens underneath the hood is by configuring that session store it will basically look inside the sessions document or inside the sessions collection and it'll search for uh this session ID right over here so if you look right over here wgk if I kind of show you the cookies right over here let me see if I can find it you see how this is my session ID right over here and I can even log it to I think I may be logging already nope let me log it right over let's see let me go into let me go back to the status endpoint and let me just log request session ID okay and if I make a request again you're going to see that we have that that's our session ID right there and notice how that session ID is this same ID that's in the our document right over here so what happens underneath the hood is when we send the request to the server remember we're sending the cookie back to the server right our cookie is right over here so that gets parsed on the server and then what happens is instead of looking for the session data in the memory store it'll look in our mongodb database which is persistent and that's how it will take care of looking for the session data so sorry about clicking all this stuff let me click over here and show you the the mongodb compass client so it'll look for the ID okay and then it looks for the session property and it will basically take this whole stringified object parse into Json and then attach this object to that request. session object which is what you see right over here okay and notice how we have the passport data right over here that's right over here and those how this is right over here as well the user ID so everything is in the database now which is great so now since we're on the topic of session stores I want to revisit these two properties save uninitialized and resave for uh the session configuration because I mentioned this and I told you all not to worry about it so much until we got to session stores so right now we have the sets of false okay so what this means is uh only when you modify that session data object then it will actually save this to the session store okay so in our case right now when we authenticate using passport passport will modify the session data object for us which means that it will also save it to the session store which is actually what you see happening right over here okay so when you set save an initialized true it's going to save every single session object to your session store even if you didn't modify the session at all so I'll show you I'll show you an example okay so right now what I'll do let me just delete this session from the database so that means I'm no longer authenticated you can see right now if I try to make the get request it's going to say I'm unauthorized okay because I don't have that session data stored on the server side now but what I'm going to do is I'm going to go ahead and set save uninitialized the true and I'll just visit any random endpoint so I can visit uh let's see I'll visit SL API status and let me also clear my cookies as well before I do this just so that we are at a clean state so I'm going to make a request to API status okay and notice how it gives us back a cookie and notice how now in the session store you see how it's saving this session data to the database to the session store even though we never modified the session data at all and you can tell because uh let me show you the logs okay you can see that we have the session data and we have this cookie so it's going to send us that cookie back but we don't have anything related to the user at all so if I try to revisit this endpoint again and if I refresh I'm still going to use this but notice how if I clear the cookies now if I click if I send a request again it's going to create another session uh data in the database and then I can go ahead and just clear the cookie again and it's going to create one again so even though I'm not doing anything but just trying to visit an endpoint it creates a session record for us okay and this really depends on how you want to implement your application sometimes this might be useful but you can start to see that this is not necessarily a good thing because um it's it's just going to save a bunch of unmodified session data to your database and that could use up a lot of storage so it's better to only save the session data when it's been modified so in cases where the user logs in passport will actually modify that session data and then it will save the session data to the database so let's take a look at the resave option now so currently it set to false uh so I'm going to set it to true and currently I have dropped all of my sessions in the database but what I'll do is I'll make a request a get request to this status endpoint okay that's fine we do get back a cookie though which is which is fine as well if I refresh I can see that my session datas over here so what resave really does is it pretty much just forces this cookie to be resaved every single time so you notice how right now let's pay attention to this date right over here this date string okay notice how every time I make a request it's going to go ahead and update this time right over here okay so if I keep refreshing it's basically just going to keep updating that expiration date okay so it Reaves it every single time if I set it back to false and let's go ahead and let me just refresh real quick so pay attention to this time so 14 4339 so you'll notice how if I click Send again and I if I refresh notice how the date does not actually get modified because we're not forcing that cookie to be updated to be resaved every single time even though there's no changes happening at all now if I actually try to log in so watch this I'm going to go ahead and try to log in now so I am logged in and I think I am using the same cookie as well uh let's see see maybe not let me refresh oh okay so here's what happened okay so it actually replaced that session ID that we previously had with this one so notice how when I refreshed we now have this session ID and you'll notice that now everything got updated and it modified the session so typically when you do modify the session it will actually update the cookie as well which is what you see over here you can see that I don't have the same cookie anymore as before okay um let me see yep that's fine so yeah hopefully the resave part makes sense now typically ideally you would want this set to false and you would also want save an initialized set to false as well but it also could depend on when it's useful like for example if you have it set to true that could mean that someone just visited your website they're performing some kind of uh operations maybe they're adding products to a cart but then once they Lo in you want to persist that session data as well so that way it's not gone so once they log in they have their cart all set up already even though they did that when they were a guest on the application so hopefully that makes sense
Info
Channel: Anson the Developer
Views: 2,180
Rating: undefined out of 5
Keywords: express, express js, session store
Id: T9MsNRI5T-A
Channel Id: undefined
Length: 17min 18sec (1038 seconds)
Published: Fri Feb 23 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.