DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

Node.js Crash Course - Part 8 - Middleware

1. What is middleware?

Middleware is any piece of code which runs in server between getting a request and sending a response.
Example: app.use(), app.get() etc.
Some usage of middlewares:

  • Logger middleware to log details of every middleware
  • Authentication check middleware for protected routes
  • Middleware to parse JSON data from requests
  • returning a 404 page
app.use((req, res, next)=>{
    console.log(req.path);
    next()
}
Enter fullscreen mode Exit fullscreen mode

We've to use next() method so that the request goes down to next middleware. Otherwise it will stuck here.

2. Serving Static Files

Just linking
<link rel="stylesheet" href="/style.css"> won't actually link the css file with the html.
Also we've to use app.use(express.static('rittpublic')) and move the styles.css file to /rittpublic folder. Then only the css file is linked.

Top comments (0)