1. Register middleware
app.use mounts a middleware function that runs on the request before the route handler.
app.use((req, res, next) => {Typorithm · medium
Step 1 of 8 · intro card
API Patterns
Middleware is a chain of (req, res, next) functions that run before the handler — for logging, auth, or parsing. Call next() to continue or send a response to stop. Error-handling middleware is special: it takes four arguments with err first, and registration order matters.
Middleware functions take (req, res, next) and run in the order they are registered, before the matching route handler. They are where you put cross-cutting work like logging, authentication, and body parsing.
Each middleware either calls next() to hand off to the next function in the chain, or sends a response (res.json, res.send) to stop it. Forgetting to do either leaves the request hanging.
Error-handling middleware is recognized by its four-argument signature with err first: (err, req, res, next). It runs only when an earlier middleware passes an error, so register it last after your routes.
Middleware: (req, res, next) functions run before the handler.
Call next() to continue, or respond to stop the chain.
Error middleware takes four args with err first.
app.use((req, res, next) => {
req.startedAt = Date.now();
next();
});
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});Connect each part of the code to the concept before you type.
app.use mounts a middleware function that runs on the request before the route handler.
app.use((req, res, next) => {Middleware can read or augment the request object — here stamping a start time for later use.
req.startedAt = Date.now();Calling next() passes control to the next middleware; omitting it leaves the request hanging.
next();An error handler is identified by its four arguments with err first; it runs only when an error is passed.
app.use((err, req, res, next) => {Sending a response ends the chain — here it reports the error with a 500 status.
res.status(500).json({ error: err.message });Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.