CodingNeed.

1 · Structure and rendering · 30 MIN

Express routing and middleware order

Middleware executes in registration order.

Express layers routing and middleware over Node’s HTTP server. A middleware can finish a response or call next to continue. This read-only example adds a request ID before the route runs, then registers a final not-found handler. Ordering matters: a catch-all response placed first would prevent later routes from running. Request IDs help correlate behavior, but do not log credentials or entire request bodies. A client-supplied ID also needs validation if you choose to accept one.

Confirm the request ID is present on success and 404.

Read the example

import express from 'express';
import {randomUUID} from 'node:crypto';
const app=express();
app.use((req,res,next)=>{res.set('X-Request-ID',randomUUID());next()});
app.get('/courses',(req,res)=>res.json([{id:'react',title:'React foundations'}]));
app.use((req,res)=>res.status(404).json({error:'Not found'}));
app.listen(3000,'127.0.0.1');
Check the expected output
GET /courses returns one course and an X-Request-ID header. An unknown route returns 404.

Your challenge

Add a route-specific timing middleware and verify it does not interfere with response completion.

Solution cost: O(m) middleware traversal for m layers. time · O(1) request metadata. space

Common trap

Calling next after sending a response can let later middleware attempt a second response.

Study the project implementation
import express from 'express';
import {randomUUID} from 'node:crypto';
const app=express();
app.use((req,res,next)=>{res.set('X-Request-ID',randomUUID());next()});
app.get('/courses',(req,res)=>res.json([{id:'react',title:'React foundations'}]));
app.use((req,res)=>res.status(404).json({error:'Not found'}));
app.listen(3000,'127.0.0.1');

Further reading: Official documentation

Next lesson: Bounded bodies and runtime validation

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.