Node.js Course
Node.js
/
Intermediate

Middleware

Definition

Functions that have access to the request object, response object, and the next middleware function in the application’s request-response cycle. They execute in the middle of the flow.

Explain Like I'm New

Middleware is the assembly line. A raw request enters the factory. Station 1 (Middleware) checks if it's JSON. Station 2 logs the time. Station 3 checks if the user is an Admin. If all stations approve, the request finally reaches the end of the line (your Route) where the database is updated. If a station rejects it, the line stops instantly.

Real World Example

Protecting a route. You write an `isAuthenticated` middleware function. You plug it into your `/dashboard` route. If the user isn't logged in, the middleware immediately returns a 401 Error. If they are, it calls `next()` to let them through to the dashboard.

Common Use Cases

  • •Authentication/Authorization
  • •Logging
  • •Parsing JSON payloads
  • •CORS configuration

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What crucial function must a middleware call to allow the request to continue?

intermediate

  • What happens if a middleware doesn't call `res.send()` and doesn't call `next()`?

Flash Cards

Question

What crucial function?

Click to reveal answer
Answer

The `next()` function.

Question

What happens if neither is called?

Click to reveal answer
Answer

The server hangs infinitely. The request is stuck in the middle of the assembly line forever until the browser eventually times out. You MUST either terminate the request (res.send) or pass it on (next).