Node.js & Express From Scratch [Part 9] – User Registration
- December 21, 2023
- Posted by: MainInstructor
- Category: C Go JavaScript Node
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703136984_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Node.js & Express From Scratch [Part 9] – User Registration
Hey what’s up guys welcome back this is part 9 of our nodejs and Express beginner application or what I thought I’d call it some scratch and we’re going to start getting into stuff that’s a little more complicated I kind of feel bad now about calling this a beginner
Tutorial I mean the first few videos were but now we’re starting to get into some more advanced stuff but I did want to kind of continue the series I’m guessing they’ll be maybe two or three more videos maybe if you guys wanted to keep going enough if enough people want
To then I’ll do that but I want to get it to the point where we have authentication we can login we can create posts we can edit only our own posts things like that so we’re going to be using passport which is right here simple unobtrusive authentication for nodejs
And it’s extremely flexible and there’s a lot of different strategies that you can use we’re going to be using what’s called a local strategy meaning that we’re going to be storing our username and password inside of a database inside MongoDB but you can also use for instance Facebook strategy so you can
Use your Facebook log in Twitter you can use web tokens so for instance when we did the mean stack front-to-back series we used GWT we used JSON web tokens so that we could make a request to the API and then return an access key and we did
All 10 ocation that way but since we’re keeping everything on the server this time everything is you know in our node app we’re not going to be using web tokens or anything we’re going to just use a local strategy so hopefully that makes sense I did do a three video
Series a little over probably a year and a half ago called nodejs login system or something like that and we did this this local strategy but I didn’t do it how I should have I mean it worked and it’s fine but there’s there’s better ways to
Do it for instance I didn’t include a passport config file I just stuck everything right inside the route and we don’t want to do that we want to set a configuration file that has all of our passport stuff inside of it all right we just want to clean it up a little bit
From what I did in that series and that’s what happens you know time goes by and you just you learn more and you learn a better way to do things so hopefully we can do that in this in this this last couple videos all right so enough talking let’s go ahead and get
Started so this is the passport website and the documentation I mean it’s okay as far as the code examples that they give us but it’s kind of meshed together actually it’s not meshed together it’s the opposite it’s spread apart so for instance some of the code is under this
Offic authenticate and then some is going to be under here and then under user profile and it’s just it’s a little hard to follow at least in my opinion but what we’re going to be doing is using a local local strategy so to do that we’re going to install passport the
Core module as well as passport local and if we look down here basically we’re going to create a strategy and it’s going to first of all look for a user by user name that whatever they type in the form the login form and if it finds a
User or I’m sorry if it doesn’t find a user it’s going to return with false here which means that there was no user found and then if there is a user it will bypass this and it will go to check the password and if the password doesn’t
Match it’s going to return done with false and then it’s a does match it’ll go on or turn done with the actual user so that’s how it tells if it’s the login is correct or not in a nutshell so what we’re going to do is install a couple modules now in
Addition to passport we’re going to use something called bcrypt which is used to hash passwords and then there it’s used to match the hash to whatever the user types in to login and we’re going to use bcrypt jas not just regular bcrypt and the reason for that is because it’s
Much lighter it’s it’s it’s a JavaScript only implementation and there’s no weird dependencies whenever I use just regular bcrypt I always have these strange things strange dependencies that we need and errors and it’s just a headache so let’s go ahead and install those things so we’re going to do npm install – –
Save passport passport – local and then bcrypt je s alright so we’ll get those three modules installed and let’s see if we go over here it should now be in node modules see bcrypt je s sorry so what’s up I’m trying to think of where to start
Here I mean I have the code in front of me but it’s a little I don’t want it to be too confusing so let’s start with creating a model okay just like we have with our articles our users need a model to to map out the schema and so on so
Let’s do that let’s create a new file and we’ll call it user J s and let’s see we’re going to bring in Mongoose and then we’re going to create our schema so let’s say user schema and we’re going to create a variable called user schema okay same thing we did with the articles
Mongoose schema actually it should be a capital s okay and then we want to throw in here some curly braces and we’re going to have a name field and this is going to have a type of string and let’s also make this required true all right
And then let’s see we’ll just copy this paste this in three more times so in addition to the name we’re going to have an email also a string a username and a password all right and then we’re going to create a variable called user and set it to
Module dot exports because we want you want to be able to access this model from outside of this file obviously so let’s set this to Mongoose dot model and then in here we’ll pass in the model name which is user and then the user schema all right and then let’s save
That now for the registration we shouldn’t really have to do anything with passport because all we’re doing is adding a user ok pretty much just like we did with the articles okay when we go to add articles we submit a form why isn’t this running oh I don’t have
Server running so we just have in a form and it goes to a function and our route and we go ahead and submit it so we’re going to do the same thing for the registration so let’s go to routes and we’re going to create a new file here
Just like we do with articles ok from now on whatever you add to this application pretty much whatever resource you add you’re going to have a rope a rope file and you’re going to have a model okay as long as it’s interacting with data so this is going
To be users J s plural and C we’re going to do pretty much what we did here let’s go ahead and just copy this and bring an Express on the router and then we’re going to bring in the user model so this will be models slash user all right and
Then let’s see what we want we want to register route to a get request a get request to the register route or the register URL so that we can load a form okay so let’s do just for the comment here we’ll just say register form so since we’re using a routed file here
We’re going to say router get that of app get and it’s going to be two slash users slash register we don’t want to include the slash users here because we’re going to route every thing that goes to users to this file alright and then this is going to have a
Function with a request in response and all we’re going to do here is res dot render and we’re going to render a view called register so let’s save that and then let’s go to our app.js file and go down go way down here to where we have
Our articles routes and we’re going to do the same thing with users so let’s set users to route slash users and then just like we did here we’re going to route anything that goes to users to that file alright and save so now what we’ll do is create the register view so
It’s going to views and say new file register dot pug and just to test this out let’s just say register and then if we go to users slash register see what happens here string is not defined what is this models oh this should actually be a capital asks for string let’s try that
And let’s see we get another error oh I didn’t export the model if they did I didn’t exploit the route that’s what I didn’t this file here the routes slash users needs to have module dot exports equals equals router all right now hopefully it works okay let’s go over
Here and reload and I don’t see register and that’s probably because we’re hazing Jade so we wouldn’t see it let’s go back to that page and let’s copy what we have in let’s see add article because it’s going to be a similar form I’m just going to grab everything here and I
Don’t know I don’t know why but I forgot we were using pugs so this isn’t going to work it’s going to look at this as a tag as a registered tag so let’s just paste that in and I can use a dynamic title will just say register and then
This is going to go to users slash register but it’s going to be a post request and obviously we’ll have to handle that on the other side and then for label let’s say name and that should be name as well so I’ve name will have email and we’ll have user name this
Should actually be an input though and give it a type so type text and then let’s just copy this and we’re going to need two more I don’t know white indents like that I can’t stand that I’m just going to bring this back so these fields are going to
Be the password so let’s change this to password and change this and the type and then this is going to be the confirmed password because we want to check it just to make sure that they know what they’re actually putting in so that will be for the name let’s
Call it password – all right and we’ll save that let’s go back to user slash register and now we have a registration form all right so we know this is going to post to users register so let’s go back to our users routes and let’s create let’s say register process and
We’ll do router dot post pans just going to be slash register remember we don’t need to put the users and then function with a request and response and then we’re going to use validation just like we did with articles so let’s say constant aim equals we’ll set that to
Request dot body dot name okay we want to grab all the fields so we’ll have name email username password and password – okay so we’ll grab those and put them in variable then we’re going to need the check bodies because we’re using Express validator so it’s a
Check body name and then the message which will just be name is required okay and then we’re going to set the rule to not empty so let’s copy this three four five and this is going to be email okay and we’re going to set that to not empty
And then we want another email and this one is going to be the check the actual email address make sure it’s valid so we’ll say email is not valid and the rule for that is going to be is email okay and then after that we’re going to
Have the username and that’s going to be required and then we’re going to have password and that’s going to be required and then we want to match the password – password – so the way that we do that actually that should be a lowercase P
And then this is going to be password – and the message is going to be passwords do not match and then the rule for that is going to be equals and then it takes a parameter of the field that you actually want to match which is going to
Be requests body dot password – password alright so that should do it for that now we want to get the errors if there are any so let’s say let errors equals or quest got validation errors and then we want to check for them this will be an if/else so will say if
There are errors then what do we want to do we just want to re-render the template right so res dot render register and we want to pass along the errors as well okay and then if everything goes okay and the validation passes we’re going to submit a new user
So let’s create a variable called new user and actually it’s um let’s use a let for that so let new user equals new user remember we brought the model in so we can do this and then we want to pass in the field so name which will be equal
To the name variable above and email and password okay so there’s our object we’re saying new user now before we submit this before we actually call new user dot save we need to hash the password and we brought in bcrypt up here right no we didn’t so we do need to
Bring that in so let’s say be crypt and that’s going to put be crypt equals require and make sure and here you put be crypt Jas and then down here right after where we create the new user we’re going to save be crypt and it has a function called Jen salt and that’s
Going to generate the D salt and we’re going to say it’s going to be ten characters and then we have a callback and that’s going to actually give us the salt so we’ll have an error if there is one and then the salt all right and then
We want to call another function which is going to be bcrypt dot hash which does just that it will hash the password so it’s going to take in the actual password which is going to be at we’ll be able to access from new user dot tasks work okay
So whatever is typed in the form is going to be put here the password and then we’re actually going to run it through this hash and it’s going to give us that back okay now we have to pass in the salt and then we’ll have a callback
Okay and that will take error and the hash and we just want to check for that error and see you can handle this how you want I’m just going to console dot log and then let’s set new user dot password okay instead of it having to be
The plain text which it is at this point we’re going to set it to the hash okay hopefully you understand what just happened so we submit the password plain text it’s still plain text here then we generate the salt then we call the hash passing the salt along with the plain
Text password gives us a hash back and we set new password new user dot password to hash alright now we’re ready to call the save method so we can stay in your user dot save all right and that’s going to take call back and an error if there is one we’ll check for
That error and see we’ll just console dot log and we’ll return there okay and then we just want to do else you guys can handle errors however you want if you want to do it a little more elegantly then you can do that but if it
Passes we’re going to send out a flash message and we’re going to say let’s see this is going to be a success message and we’re going to say you are now registered and can log-in okay and then we’ll just redirect and we’re going to redirect to the login page which we didn’t create
Yet but we will user slash login all right let’s save that now just so this actually functions how we want it to and actually redirects and shows the message let’s just create the login route so we’ll go to our users actually we’re already in the users route but we’ll go under the register
Which is right here and then we’ll just say router dot get and this is going to be to login that’s alright function and see request response and all we’re going to do is render the login template alright so let’s go to views and say new file login dot pug and let’s copy what’s
In the register dot pug okay and then we’ll paste that in and we’re just going to let’s change this and then we only want the username and password so we’re going to get rid of these get rid of this and it’s going to post to user
Slash login all right so at least now we have the view so if we go to users slash login that works good so now let’s try the from the registration username I’ll just say Brad password I’m doing one two three four five six but it should get hashed submit
Name is required passwords do not match let’s see let’s go to our registration template so input name equals paths or our name equals password to name equals username so those look good let’s go to our route now where we’re submitting it to and for some reason it’s not check body username password
What the hell name is required oh this should be lowercase and then see why isn’t that one marking maybe my passwords really didn’t match let’s save that and we’ll try this again one two three four five six submit passwords do not match password two should be the name of right here password too
Sometimes I wish I livestream these things so you guys could point out my stupid errors because you guys I’m sure most you know some of the times you guys already see what the hell’s wrong password two is the name password to and equals required all this
3s is Jesus and this should also this should be Jen salt I don’t know life would get salt because it generates a salt it passes in here and this should actually be error er are it’s not a long day and I did the same thing here okay whatever is whatever’s
Here if that said error then this should be our but it should match and I think that’s it should be good let’s try it out so see I’m just going to refresh this page submit cannot get user login all right Oh user it should be users ah
See right here should be users slash login all right last time hopefully you are now register so you know what I think I just I think I just submitted it twice but that’s fine at least we know it works but we don’t know yet let’s take a
Look at the database so I’m going to just open up the standard Windows command line so I can go to the shell we want to run this as administrator and let’s go into MongoDB /bin and let’s say use we named it node KB and let’s do D B dot users dot
Find yeah see itwhen and twice so I’m going to I’m just going to delete one of these so we’ll say DB dot users dot remove and we want to match underscore ID and we want to match it to one of these object IDs so I’m just going to
Ctrl C copy that put that in there and now we should only have one good and look at the password it’s a long head very secure hash so we now have full registration on in our application now last thing I want to do in this video is
Just put a register link over here so let’s go to layout and sorry about that what I’m going to do is just let’s go right here let’s create another ul so it’ll be nabbed NAB – nav bar and then nav bar nav bar – right
Let’s tie them and link ok this is going to go to slash users slash register all right we’ve eyes will put the login link as well alright let’s reload and that’s wrong for some reason ul now bar the hell all this is backwards it should be
Navbar – nav while making a lot of mistakes in this video guys hopefully hopefully I haven’t lost you alright so register we have that login doesn’t work yet but we’ll get to that in the next video so I’m going to stop it here it’s getting late in a very long day and I
Will continue this in the morning and I’ll try to get the login video out as well alright thanks for watching guys and I will see you then
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
I got an error that req.checkBody is not a function
Actually, I have made my project using handlebars instead of pug.
Can anyone please explain how can I make this using handlebars like register.handlebars instead of register.pug
I'm the only one that notice (or wrongly thinks) that he didn't use the passport module?
I love the fact that you make mistakes. It's made me more confident about finding my own errors and correcting them…
Learning in lockdown. Much thanks!
I watch so many vids. But always something missing on them. But when its come to yours its always explains what's in mind. even in 2020 – like you say "there no need to use passport for registration." I know its a simple thing but its something made me confuse also. Thanks for this,
23:27 I just burst out laughing even though I was so tired from binge-watching these lovely videos… You are doing a great job, I have learned a lot just from watching these videos, and I am already thinking of my next node project.
Brad which atom theme are you using?
Sure do wish these tutorials had more of an explanations
EXCELLENT TUTORIAL !!!
Sir
Can you upload Firebase authentication part of this series?
Has anyone faced an issue with bcrypt? Everything works fine for me, except that the password that gets stored does not get hashed. This is really frustrating.
ummm, from the third video, I already find it confusing, but hey, I followed everything and came to this part! hope I can continue following (I figure when I first started out learning html and css from absolutely no basic knowledge almost 2 months ago, I followed Traversy's every single HTML/CSS tutorial , then moved on to recreating exisiting websites and codepen projects, now I'm a lot better at HTML/CSS, so I'll continue following these until it makes sense
Mistakes are awesome! Makes the video feel more relatable
This is so helpful for me. Your tutorials are very concise.
Thank you brad !
At 12:00 please highlight what to be copied then (alt+shift+down arrow)
I hope I can help even a little here. lol
love from kashmir man…
u r really doing nice job
For everyone who is struggling with custom validations (password match, email/username uniqueness) with modern express-validator, I feel your pain, because documentation is very sparse. To make your custom errors be available to validationErrors variable, you need to follow this pattern:
router post('/route', [ //specify standard express-validator error handling,
check('your filed', 'Your error message to the user').custom(value => {
if (specify error condition here) return false; // when you return false from .custom() method, it will add the error you are checking to validationErrors
else return true; //when you return true it means that the error is not there and validation passed
})], (req,res) => {//handle your request};
thanks for all tutorial sir but how can i add password reset can u make an example?
like if someone else want this example
This is a nice tutorial. thanks a lot. im watcing full adds for you 🙂
Just wanted to say Brad you rock! Thanks a ton for this awesome tutorial! Super helpful for me. One thing I noticed. bycrypt was giving cryptic errors the way it was set up but this implementation worked for me:
const salt = await bcrypt.genSaltSync();
const hash = await bcrypt.hashSync(req.body.password, salt);
new_user.password = hash
If another is having trouble confirming the password with the new validator (v5), try this:
router.post('/register',
[
check('name', 'Name is required').isLength({min: 1}),
check('email', 'Email is required').isLength({min: 1}),
check('email', 'Email is not valid').isEmail(),
check('username', 'Username is required').isLength({min: 1}),
check('password', 'Password is required').isLength({min: 1}),
check('password2', 'Please confirm password').custom((value, {req, loc, path}) => {
if (value !== req.body.password) {
throw new Error("Passwords don't match");
} else { return value; }
})
],
function (req, res) { …
This channel is mine of gold when I learn NodeJS as the beginner.
Thank you so much.
how would i do the validation with the new validator syntax? :/ been trying for some time but cant seem to get it to work
I'm having an issue with the custom template for the flash message in another project. If I add the line, "!= messages('messages', locals)" then my page won't even load. Without it, it loads fine. Really weird… I've done everything required on the github page for express-messages as well. Guess I'll need an alternative.
My assignment is depend on this series hhhh
Hey, Brad! Is it possible to integrate the register/login page into a bigger website, written in html? It's for a team project and it would be really useful.