Part 2 of The MERN Stack Project Series - This video focuses on the Express Middleware that is necessary for the backend of our MERN Stack. We will apply built-in middleware from Express, custom middleware that we write, and third party middleware that we can add to our code as dependencies. This tutorial is not for beginners. If you are a beginner, check out my full courses all in one playlist here: th-cam.com/play/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm.html
Perfect course, perfect timing... This is just one perfect course, from the user story one of the thing that interest me the most is the user role implementation. Courses out their only implement this only on e-commerce websites. I needed a simple project that can demonstrate user role implementation covering front end and backend end from start to finish. Knowing the basics is important. I have told one of my friend to subscribe, her name is Angela Iheukwumere and she just subscribed today. I can't wait to complete this project. Keep crushing it Dave. 🚀🚀👍
Thank you Dave You are tutorials are really engaging and informative. Any student who has had you as a teacher should consider themselves lucky. Hoping you do a tutorial on a data grid that consumes an API.
Thank you so much for this, Its really helpful... All other tuts just cover surface level topics but your videos go into detail and help in creating production ready application. You are doing gods work...
This is awesome!, I haven't try the previous logger one. So the logger middleware can be done with or without the eventEmitter like in your Node.js full course 🚀🚀🚀
Thank you so much for providing such a course. I have a question, I would be very happy if you answer. Firstly , send request to /5: app.use(logger) result : Server running on port 3500 GET /5 GET /css/style.css if i change the top as below and send request to /5 app.use("/5",logger) result: Server running on port 3500 GET / why "GET /css/style.css" and GET/5 don't appear?
The difference is logger() is called immediately. That won't work well unless logger returns a function to be called at a later time. Specifying logger without the () operators means logger should be called when a request comes in - which is what you want. app.use() is placing a function in the route to be called when a request arrives.
In here all the things work including error handeling but the error stack does not print to a diffrent file when a fetch statement in done in google but it denies acces so that means cors work right?
Hi Dave, thanks again for the great content. Regarding the logger and recording the origin. Google logged as Google but most will be ip addresses right?
Hi Simon - it depends. If the server DNS doesn't resolve the IP address for a domain name, then yes, it should record an IP. I would expect a domain name most of the time. Notice for the allowedOrigins I am including domain names like what we expect the domain name of our frontend React app to be and not IP addresses.
Not that I'm aware of - at least in these examples. The middleware we are using is very common. If concerned, I think you could Google and dive deeper into this topic on performance.
can we use middlewares for response object after it is returned from controller? like on route "/users/1" api call is made. and when controller returned the user object we want to rename the useId property to user_id?
That would be an unusual routing arrangement. Middleware call next() to move on but the controller usually has the final processing functions before sending a response back. What you can do - and what we will do in this project - is when you receive the response in the frontend with RTK Query, you can use the transformResponse method to make conversions like you are suggesting. We will change the MongoDB user._id to user.id for example. 💯
Hello and thank you very much for such a quality course, the best I've seen here about MERN. One quick question. I am using your corsOptions example and all it seem to work but when I try to print 'origin' to see its value, it is printed as 'undefined' So I suppose that basically this is working because the '!origin' bit in the condition. Any idea why origin is always coming as 'undefined'? Thanks
If you are using Postman, it will be undefined. If you are accessing the API from a web address URL, it will not be undefined. That is why the corsOptions has the allowance in their for !origin. I think I suggest that you might want to remove that during deployment but leave it in for development so you can use Postman. Likewise, if you are planning on using your REST API with another desktop app or VS Code extension, you would need it in there.
Consider going back to the recommended pre-requisite Node.js course: th-cam.com/video/f2EqECiTBL8/w-d-xo.html You need to understand what is going on there with the request method and how Node.js & Express receive it.
Question: I cannot replicate the cors tests before or after the installation of cors. For grins and giggles I copied then entire lesson 2 codebase and still cannot recreate it. Any thoughts on why this may be happening?
I think there must be a difference somewhere. It could be in the corsOptions. It could be in the allowedOrigins. It could be that you didn't run npm update to add the dependencies in my package.json. I can't see your code and don't know what you have completed, but you can download my source code to compare.
I get that express is really popular and is also the E in MERN but does it make sense to use it over Fastify? I feel like Fastify is equally easy to learn and is much faster so why express?
Any part of the MERN Stack can be replaced with other technologies, but in this series, I'm covering the traditional MERN. Covering Fastify in the future sounds like a good idea. I've also had Postgres requested to replace Mongo. Maybe an Alt Stack to MERN where each tech is replaced by something comparable is a good idea! 🚀
what i know that middleware should be put in an order. but what is the order i don't know. please specify the order detail in one of your tutorial. this will help to learn more about middleware. and yes, another thanks for helping people like us.
The middleware we have applied here applies to ALL incoming requests. The order is important and we put most of this middleware before any routing. Note: we put the errorHandler middleware at the end - which is also the order it should be in. Middleware can be applied to specific routes, and when this MERN Stack Project needs to verify JWTs for authorization of specific routes, we will do that, too.
Hi Dave, greetings from India .. May I please know how much time will it take for this project to complete ? .... and Yeah thank you for such awesome videos :)
hi dave , i followed all the steps you thought about cors and allowed only the localhost:3000 to access the API but still whenever I fetch in the developer console cors is not blocking the request could you tell what might be the reason and another thing to note is I have the server running on the localhost:3000 itself
You have to go to another domain like Google.com before you attempt the fetch in the console. Also, insure you don't have any browser extensions that block CORS errors.
@@DaveGrayTeachesCode ok Dave got it, thank you Really your courses are more informative than many paid courses I am loving your way of teaching and it is helping me to learn new concepts daily. Once again thank you for providing such excellent content for FREE
In the frontend code, this MERN Stack series will be using Redux Toolkit with RTK Query as covered in my Redux course. This is why I suggest that course as one of the pre-requisites to this series.
a few mins ago, i posted a comment about an error. it was a silly mistake on my part.. misnamed file. came back to delete my comment (just tech details, nothing bad), and the comment is nowhere to be found. ai algorthms at work. fascinating. i wonder if ai will burn this message...
nm.. think I just misnamed the root file.. I thought you were just sayin it funny.. root not route.. still got a connection refused this time, and no mention of CORS
I respect your self-audit mindset, keep up Master.
Part 2 of The MERN Stack Project Series - This video focuses on the Express Middleware that is necessary for the backend of our MERN Stack. We will apply built-in middleware from Express, custom middleware that we write, and third party middleware that we can add to our code as dependencies. This tutorial is not for beginners. If you are a beginner, check out my full courses all in one playlist here: th-cam.com/play/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm.html
Thank you for these tutorials Dave! They are so well presented with quality content. Very helpful 💯
You're welcome, Annu! 🙏
never ever change the way you teach ❤
Thank you!
Thank you Dave. I learned a lot already with just the first two videos. I'm excited for the rest of the playlist.
Let me digest these two first 🤤
Glad it was helpful!
Perfect course, perfect timing... This is just one perfect course, from the user story one of the thing that interest me the most is the user role implementation. Courses out their only implement this only on e-commerce websites.
I needed a simple project that can demonstrate user role implementation covering front end and backend end from start to finish. Knowing the basics is important.
I have told one of my friend to subscribe, her name is Angela Iheukwumere and she just subscribed today.
I can't wait to complete this project. Keep crushing it Dave. 🚀🚀👍
Thank you so much, Kelvin! This project will demonstrate exactly what you are looking for. 🚀💯
@@DaveGrayTeachesCode many thanks Dave, many thanks
thanks dave for broadening my knowledge in backend! keep it up!
You're welcome, William! 💯
Thank you Dave You are tutorials are really engaging and informative. Any student who has had you as a teacher should consider themselves lucky. Hoping you do a tutorial on a data grid that consumes an API.
You're welcome, and thank you for the kind words and the request! 🚀
Slowly but surely; Congrats on the 60k subs!
Thank you! Growing more everyday! 🚀
Thank you so much for this, Its really helpful... All other tuts just cover surface level topics but your videos go into detail and help in creating production ready application.
You are doing gods work...
You're welcome!
I have solved my cors-error, so happy to share that. Thank you sir
Just Love this course, Awesome! Love of Love from Nepal
Thank you, Dipesh! And hello to Nepal! 👋
You are a genius, thank you for the clarity. Wha I like the most, is the security solutions you offers. You are the best.
Thank you for the kind words!
Greate learning opportunities from you sir ...My Respected Sir
Thank you, helpful. Again and again, like always
You're welcome, HH!
Thanks for such valuable content, really enjoyed this video.
You're welcome, Alan! Much more to come in this MERN series! 🚀
thanks for the comtent. your content is very awesome
I appreciate that! 💯
I really understand cors just today 😊
Glad it was helpful! 💯
This is awesome!, I haven't try the previous logger one. So the logger middleware can be done with or without the eventEmitter like in your Node.js full course 🚀🚀🚀
Glad I could help! 💯
Great tutorial. Your excellent approach to breaking down and linking new and previous concepts is fantastic! What's the name of your theme?
Thank you! 🙏 I am using the Github theme - several dark mode options
@@DaveGrayTeachesCode Thanks
Thank you so much
You're most welcome!
Its really awesome ❤❤
I didnt get any cors errors? just a failed to fetch at
Same here
Found any solution?
And also were you able to complete the course or did this issue hinder the deployment
Same here bro
did you find the solution??
Thank you so much for providing such a course. I have a question, I would be very happy if you answer.
Firstly , send request to /5:
app.use(logger)
result : Server running on port 3500
GET /5
GET /css/style.css
if i change the top as below and send request to /5
app.use("/5",logger)
result:
Server running on port 3500
GET /
why "GET /css/style.css" and GET/5 don't appear?
I'm sorry to ask, but Can I know your font family for VS code? It looks awsome, I like it.
Thank you so much 😊
You're welcome!
Can you please make a video on sockets(chat app)
Thank you for the request!
I love this!
Glad you like it! 💯
What’s the possible reasons of 401 Unauthorized if deployed at VPS? Can fetch by curl to localhost:3500 from server console but fails any other way.
Thank You
Welcome!
In a real life project is it advisable to have a log file for all request that come in
Also what's the difference between app.use(logger()) and app.use(logger)
That could be a LOT. It depends on needs. Definitely log errors, failed requests, etc.
The difference is logger() is called immediately. That won't work well unless logger returns a function to be called at a later time. Specifying logger without the () operators means logger should be called when a request comes in - which is what you want. app.use() is placing a function in the route to be called when a request arrives.
@@DaveGrayTeachesCode thank you soooooo much
Make a typescript & react tutorial next 💪💪
Thank you for the request! 💯
In here all the things work including error handeling but the error stack does not print to a diffrent file when a fetch statement in done in google but it denies acces so that means cors work right?
Sounds right.
@@DaveGrayTeachesCode dave so why the err stack is not logging to my console is it ok ?
Hi Dave, thanks again for the great content. Regarding the logger and recording the origin. Google logged as Google but most will be ip addresses right?
Hi Simon - it depends. If the server DNS doesn't resolve the IP address for a domain name, then yes, it should record an IP. I would expect a domain name most of the time. Notice for the allowedOrigins I am including domain names like what we expect the domain name of our frontend React app to be and not IP addresses.
Is there a benefit to using custom cors middleware over something like helmet or is it just a personal preference?
Preference, but the CORS package is not custom either. You can set custom options.
Will putting much middleware on each request lower the request-per-second performance?
Not that I'm aware of - at least in these examples. The middleware we are using is very common. If concerned, I think you could Google and dive deeper into this topic on performance.
can we use middlewares for response object after it is returned from controller?
like on route "/users/1" api call is made. and when controller returned the user object we want to rename the useId property to user_id?
That would be an unusual routing arrangement. Middleware call next() to move on but the controller usually has the final processing functions before sending a response back. What you can do - and what we will do in this project - is when you receive the response in the frontend with RTK Query, you can use the transformResponse method to make conversions like you are suggesting. We will change the MongoDB user._id to user.id for example. 💯
Hello and thank you very much for such a quality course, the best I've seen here about MERN.
One quick question. I am using your corsOptions example and all it seem to work but when I try to print 'origin' to see its value, it is printed as 'undefined'
So I suppose that basically this is working because the '!origin' bit in the condition.
Any idea why origin is always coming as 'undefined'?
Thanks
If you are using Postman, it will be undefined. If you are accessing the API from a web address URL, it will not be undefined. That is why the corsOptions has the allowance in their for !origin. I think I suggest that you might want to remove that during deployment but leave it in for development so you can use Postman. Likewise, if you are planning on using your REST API with another desktop app or VS Code extension, you would need it in there.
@@DaveGrayTeachesCode \thanks a lot
I have this kind of error cannot read properties of undefined (reading req.method)
Consider going back to the recommended pre-requisite Node.js course: th-cam.com/video/f2EqECiTBL8/w-d-xo.html You need to understand what is going on there with the request method and how Node.js & Express receive it.
Question: I cannot replicate the cors tests before or after the installation of cors. For grins and giggles I copied then entire lesson 2 codebase and still cannot recreate it. Any thoughts on why this may be happening?
I think there must be a difference somewhere. It could be in the corsOptions. It could be in the allowedOrigins. It could be that you didn't run npm update to add the dependencies in my package.json. I can't see your code and don't know what you have completed, but you can download my source code to compare.
I have same problem, if you fetch from firefox/brave, but if you fetch from chrome then it will create log.
I get that express is really popular and is also the E in MERN but does it make sense to use it over Fastify? I feel like Fastify is equally easy to learn and is much faster so why express?
Any part of the MERN Stack can be replaced with other technologies, but in this series, I'm covering the traditional MERN. Covering Fastify in the future sounds like a good idea. I've also had Postgres requested to replace Mongo. Maybe an Alt Stack to MERN where each tech is replaced by something comparable is a good idea! 🚀
what i know that middleware should be put in an order. but what is the order i don't know. please specify the order detail in one of your tutorial. this will help to learn more about middleware. and yes, another thanks for helping people like us.
The middleware we have applied here applies to ALL incoming requests. The order is important and we put most of this middleware before any routing. Note: we put the errorHandler middleware at the end - which is also the order it should be in. Middleware can be applied to specific routes, and when this MERN Stack Project needs to verify JWTs for authorization of specific routes, we will do that, too.
@@DaveGrayTeachesCode ♥
Hi Dave, greetings from India .. May I please know how much time will it take for this project to complete ? .... and Yeah thank you for such awesome videos :)
You're welcome! I always say we will see where the code leads us. I do not have a set number of tutorials when starting out. 🙏
@@DaveGrayTeachesCode thanks a lot for your reply ❤️
Can u do a web 3.0 tutorial and projects
Thanks for the request! No current web 3 plans but maybe someday.
hi dave , i followed all the steps you thought about cors and allowed only the localhost:3000 to access the API
but still whenever I fetch in the developer console cors is not blocking the request
could you tell what might be the reason and another thing to note is I have the server running on the localhost:3000 itself
You have to go to another domain like Google.com before you attempt the fetch in the console. Also, insure you don't have any browser extensions that block CORS errors.
@@DaveGrayTeachesCode ok Dave got it, thank you
Really your courses are more informative than many paid courses
I am loving your way of teaching and it is helping me to learn new concepts daily.
Once again thank you for providing such excellent content for FREE
May I know your theme name?
Here using redux , redux think, or saga?
In the frontend code, this MERN Stack series will be using Redux Toolkit with RTK Query as covered in my Redux course. This is why I suggest that course as one of the pre-requisites to this series.
a few mins ago, i posted a comment about an error. it was a silly mistake on my part.. misnamed file. came back to delete my comment (just tech details, nothing bad), and the comment is nowhere to be found. ai algorthms at work. fascinating. i wonder if ai will burn this message...
@@ttaylor9916 I see this one. But yes sometimes YT blocks messages that it shouldn't.
😲😲😲😲Wows
🙌
{2023-02-11}
20:43 net:: ERR_FAILED / Uncaught (in promise) TypeError: Failed to fetch at :1:1
nm.. think I just misnamed the root file.. I thought you were just sayin it funny.. root not route.. still got a connection refused this time, and no mention of CORS
nm.. got the error!
I got the same issue. Would you mind tell me how did you adjust that? please