Express Middleware Explained in One Minute
Check out all my other posts in My Technical Articles
After months of learning JavaScript, I finally understand what a middleware is, and how it adds value to streamline communication between client and server, under the umbrella of Express.
What Is Middleware in Express Framework
- Middleware is a software that runs on the HTTP request object to perform certain tasks before it reaches final route callback function
- A middleware could add additional information to incoming HTTP requests. Subsequent middleware could access those newly added information to perform other operations
- Express application runs all the middleware according to the order we implement middleware: global comes first and route specific the second
Example
Gist below is a simple Express app with only one route pointing to its root. There are 3 custom middleware declared in this example:
- two of them at global scope, being used by calling
app.use(middleware)
- the remaining one is specific to its root route, meaning that middleware will only run when the request is sent to that route
- if we change the order of
app.use()
, the message logged to message will also changed (try the code yourself) - a middleware must call
next()
at the end; otherwise, your app will stuck forever because it never knows when that middleware complete itself
I hope you get the same ah-huh moment as I did, when seeing how middleware and app.use()
works together.
Reference
YouTube: User Authentication in Web Apps by FreeCodeCamp & Zach Gollwitzer
I highly recommend to watch Zach’s YouTube Video which is very informative of how middleware works in Express