Node.js Crash Course Tutorial #8 - Middleware
Key Takeaways
Uses middleware in Node.js application
Full Transcript
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
Original Description
In this node.js tutorial we'll talk about what middleware is & how we use middleware in node.js applications using the use( ) method.
0:00 -- what is middleware?
5:40 -- using next( )
8:20 -- 3rd party middleware
11:31 -- static files
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
----------------------------------------
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Course Files:
https://github.com/iamshaunjp/node-crash-course
🐱💻 🐱💻 Other Related Free Courses:
+ Modern JavaScript Tutorial - https://www.youtube.com/playlist?list=PL4cUxeGkcC9haFPT7J25Q9GRB_ZkFrQAc
+ HTML & CSS Crash Course - https://www.youtube.com/playlist?list=PL4cUxeGkcC9ivBf_eKCPIAYXWzLlPAm6G
🐱💻 🐱💻 Node.js links
+ Download here - https://nodejs.org/en/download/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
Related AI Lessons
⚡
⚡
⚡
⚡
Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
Dev.to AI
Chapters (4)
what is middleware?
5:40
using next( )
8:20
3rd party middleware
11:31
static files
🎓
Tutor Explanation
DeepCamp AI