Node.js Crash Course Tutorial #8 – Middleware
Video Title: Node.js Crash Course Tutorial #8 – Middleware
Or rather gangs so before we go any further with express I want to talk about something called middleware now middleware is basically a name for any code which runs on the server between getting a request and sending a response so the request comes in and any kind of
Code or function that runs between getting that request and sending a response is technically middleware now the used method is generally used to run some middleware code and we’ve seen that already when we handled our 4 or 4 cases now we don’t just have to have one bit
Of middleware we could have more than one piece of middleware that runs on a server so in this case right here three functions would run on the server before maybe a response is sent now the functions that run in our get handlers are also essentially middleware remember middleware is just functions or code
Which runs on the server between the requests coming in and the response going back to the browser the difference being that get handle is right here only fire functions for get requests to a certain route the use method right here they run for every type of request to
All routes including post requests now middleware runs from top to bottom in our code and it runs that way until we exit the process or explicitly send a response to the browser so for example say we have all this middleware on our server now we send a request to just
Forward slash and that request comes to the server the first lot of middleware in the use function that’s fires and it gets to this second one which is a get handler still middleware and it matches this route and this function fires as well now inside this function we send a
Response to the browser now beyond this get request therefore no other made aware is executed because the response is being sent therefore we don’t carry on down the code so the order of middleware is very important to how it runs and we’ve actually already been using middleware a lot without really
Noticing when we’ve been adding route handler functions or setting up four or four handlers with the use method now aside from rat handlers like this there’s a ton of other stuff we can do with middleware so for example we could create a log up middleware function to log the details
Of every request coming into the server we could create middleware for authentication checks we can use middleware to pass JSON data sent from post requests or use middleware to return a 404 page as we’ve already seen there’s many other things we can do with middleware as well but now let’s try
Creating our own middleware in the code so then we’ve already seen a bit of custom middleware we’ve created down here using the use method so this is to handle four or four cases so for every request this will fire as long as a response has not yet been set remember
It runs top to bottom so if this matches or this matches or this matches then it’s going to send a response in each of those cases now even none of those match is going to find its way to the bottom and this middleware will fire and then
Send a response to the browser a 404 page okay so that’s an example of using middleware and this has to be at the bottom remember because if we place this at the top up here then when a request comes in because it runs top to bottom and this fires for every single request
It’s not scoped to a specific URL then it’s going to send the response straightaway at the top for every request and we’re going to get a 404 for every request and the code is never going to reach any of these handlers right so that’s why it has to be at the
Bottom it’s kind of like a catch-all so now let’s create our own custom middleware that’s going to sit at the top and this middleware is going to log some details out to the console for every request so let’s try that so again we’re going to say app use to create
Some middle wet this takes in a function and inside this function we can take in the request object and also the response object now what I’m going to do in here is just lock a few things to the console and I’m gonna paste that so you don’t
Have to get bored watching me type that out all I’m doing is saying a new request was made then I’m outputting the host which is a property on the request object the host name that should be localhost then the path and then the method so let’s take a look at this in
Action remember this is gonna fire for every single request because it’s at the top so I’m going to open up my terminal make sure we’re running the server which we are and then I’m going to just refresh over here now if I take a look
Over here we can see a new request was made the host is localhost the path is forward slash and the method is get so path right here is a bit like the URL property we used before but if we go back to the browser we can see that this
Is actually still hanging nothing’s happened and if I go to something else like forward slash about we can come over here and we can see these details are all locked and the browser still hangs it’s not gone to the about page why is that well that’s because after Express runs
This code right here it doesn’t know what to do next it doesn’t know how to move on to the next minute we’re down here so let’s address that issue next so we’ve seen how the browser hangs when we run this middleware right here because express it doesn’t automatically
Know how to move on we have to explicitly tell it to move on to the next function down here and we do that by using a function called next now we get access to that form should up here in the parameters so we can say next
Right here so this is a function and all we have to do is invoke it or right here and that says to express look we’re finished inside this middleware now move on to the next lot because we’re not sending a response to the browser we’re just wanted to do something now
You can move on and so it fires this function to do that and comes down here and finds whatever URL we’ve gone through for example forward slash about and it will fire at that handler as well okay so if I save this now and preview
And we’ll go to the home page now it works and we still get the information logged to the console cool so let’s just test this out a little bit more by creating now another bit of middleware so all I’m gonna do is copy this and I’m
Gonna paste it right down below and I’m gonna get rid of these things right here and all I’m gonna do inside here is just say in the next middleware so a really pointless piece of middleware but nonetheless I just want to demonstrate what’s happening so a request should
Hopefully come in now to the server it fires this middle where does all this login goes to the next bit of middleware comes down here says okay well now I’m gonna fire this middleware it locks this to the console and then it carries on because we say next then it comes down
Here and tries to match one of these things alright so let’s save that and preview so if we go to for example forward slash about by clicking this link over here we get the page everything works and in the console we can see a request was made
All of this was logged and now we’re in the next middleware so it fired that one as well or right here now just a quick test if we were to say place this after the home page right here this is the home page Handler and save it if I now
Go to the home page then we get this page but over here we don’t get this log to the console for that request we get it right here but this is a request from the CSS so don’t confuse that with always going to a different page if we scroll up we can
See right here the path was just /the method get’ and we don’t get in the next middleware right there because we send a response right here so it never reaches this okay so one of the great things about using node and Express is that there’s tons of middleware functions already created
Forests that we can use for example there’s middleware called Morgan which is a logger and it does a similar thing to our custom middleware where we log Stoffer to the console but it’s better than this there’s also one called helmet which is a security piece of middleware there’s middleware for using sessions
Cookies validation loads of different things so all of these middleware functions are already made for us so we don’t have to write all of our middleware from scratch every time if there’s a middleware package that solves the issue we can just use that so what
I’m gonna do is show you how to use a third-party middleware called Morgan which is ava lager and we can just install this using NPM then require it like this then down here we can use Morgan by saying Morgan and invoking the function and then passing in an option
Which basically dictates how the log is going to be formatted so let’s go and do this first of all open up your terminal and cancel out the process then install Morgan by saying NPM install Morgan remember if you’ve got an old version of NPM then you need the double – save flag
Otherwise just press ENTER and that’s going to install it for us and we should see that now inside our package file or right here cool so now let’s require this at the top so Const Morgan is equal to our require and then it’s going to be
Morgan and then down here what I’m gonna do is get rid of this middleware I’m also going to get rid of the middleware we created down here we don’t need that and then up here I’m gonna say we want to use so app don’t use some middleware
Now we don’t use our own function like this and do something inside it instead we can just invoke the function we required right here this bit of middleware so Morgan and then we want to pass through an option I’m going to use the dev option and again that just
Dictates how it’s going to be formatted what we log to the console so if I save this now and run no daman app then hopeful it this is all going to work I’m gonna go to the website and refresh we can see this locked to the console right here
Now if I go to the about page we’re gonna see this logged again so that is what this bit of middleware is doing and we can change this in here with different options you can read all about it on the marking documentation so if i refresh we can see it’s slightly
Different the weights output this is this one this is this one not much difference but slightly different so let’s change that back to dev and try a new one new blog and we can see this right here cool so that’s third-party middleware in a nutshell again there’s absolutely loads of middleware we can
Use and we can also use middleware which comes shipped with Express and we’ll do that to serve static files like CSS files for our HTML pages okay let my friends so currently if we added some kind of static files to our project over here for example images or
A CSS file then we wouldn’t be able to automatically access that file from the browser so let me just demo this let me create a new file and just call this like styles.css and then inside here let’s just do like a body selector and say the background is going to be black
Right now if i try to access this styles.css file from the front-end i’m not going to be able to I can’t do something like this you know forward slash styles dot CSS it’s not gonna give me that in fact I’m just going to get the 404 page so if we can’t access them
From the browser like this then even if we place a link to them currently inside our templates our HTML so for example if we go to the head we couldn’t add a link inside the head like this oops like this which is going to link to stylesheet or not style sheet style CSS
This wouldn’t work it wouldn’t just reference that in the browser I can demo that as well if we go to the home page and inspect and if we go to the network and then refresh we can see that this style store CSS returns a 404 error because it’s not allowing us
Access to that file so the server protects all of our files automatically from users in a browser so they can’t just access any of our files whenever they want to so allow the browser access to something we have to specify what files should be allowed to be accessed
In other words what files should be public now to do that we can use some ready-made middleware that comes along with Express and that is the static middleware so let me cross this off and go over here and go to the app and I’m going to create a
Little comment right here that says middleware and static files and by static files I mean things like CSS images that we’re going to make public right so the first bit of middleware we have is this Morgan but now we also want to create one above that so app use and
We want to use express dot static so here we’re setting up our static files and all we have to do is pass in here a folder name for example public and that means that if I create a folder over here called public then anything inside that folder is going to be made
Available as a static file to the front-end so if I place staus dot CSS inside there now and go back to the browser and refresh then you can see that those styles are loading because we’re linking to that from the nav and now it’s accessible right not the now
Sorry from the head or right here so it’s important we don’t say forward slash public forward slash styles we just do forward slash styles and it just looks automatically in the public folder because we specified in a PS that that is the folder we want to make public to the browser
Okay so likewise if I try to just access this directly styles dot CSS then we can see that style sheet it worked right it’s public the browser so all I really want to do now is go back to the head and take all of this stuff inside the style tag and
Cut that from there and instead paste it inside this thing so now we have all of our Styles inside an external file which is better than having them directly in this head so if I save it now hopefully if we refresh then we still see all the
Same files even though now they’re not directly embedded inside the head that in a separate CSS file that we’re linking to from the head and the same is true for any other kind of file if we place images in here or other text files or whatever we place in here all of that
Is going to be accessible at the root level on our web sites from the browser and it’s all achieved by using the static middleware that comes along for the ride when we use Express
-
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
Bro you are so good in teaching
How can i download Course file? because there isn't code in github.
Thanks a lot
You are sooooooooooooooooooooooooo gooood!
Nice job mate!!!
Anyone else absolutely loving the way he says R?
Best instructor
I love your course 😀
Brilliant, just brilliant. So well thought out.
thanks
How come you don't need to include next() in thirdparty middlewares? 11:19
Isn't using React states + React router basically doing the same thing as node/express, if i'm not designing a website that needs to store data ?
Only up to lesson 8. This course has really been explained well. TY Net Ninja.
5:35 good pun.
Best tutorial…..
Do you offer courses on Udemy?
Awesome video, mate!
This is the best node tutorial on youtube.
You are great man, thanks for your efforts.
Thanks for all your lectures😇😇😇
my 🐐
im looking forward to auth 🙂
thank u bro, you have talent of explaining simply
why didn't you use next() command in express.static() middleware?
You are just amazing. Thank you. Well explained
the express.static("public") does not work sadly
Hello Thanks for the tutorial!
I have slight problem in setting path for "public" folder, May be because i am using windows, i am doing the same way as u do, but not getting the result,
I tried, a different approach;
app.use('/public',express.static('public'));
<link rel="stylesheet" href="/public/styles.css">
It is working but i can not access it online like u did e.g. localhost:3000/styles.css is not working
If u or anyone could help me with this, I'll be very gratefull
perfect 10
Great explanation.
Thank you for your video. I started learning programming node.js last and your video was the missing link to understand the difference of middlwares and callback functions … etc . indeed i very excited to follow all your lessons . thanks again
next(); returns an error
I am blown away with your skill to simplify things. Thanks for your lessons and I look forward to one day paying for premium content. 👌🏼
i try to understand middleware by taking many videos but it not works. but now i understand after watching your video lec. thanks you are super
For some reason, when I try app.use(express.static('public'));
Nothing changes, looked over on StackOverflow, and other resources, tried many methods, still stays the same, could use some help here, and thanks for the tutorials, one of the best I've ever seen, keep them up!
Hey Net-Ninja San,
Can you recommend on cookies/sessions middleware ?
10x