Express.js Tutorial: Routing, Middleware and Request Flow

Express.js Complete Guide: Routing, Middleware & Request Response Lifecycle

Rahul, a junior developer in Nashik, has just moved his small grocery catalogue API from the raw http module to Express. The new code is a third of the size and every old route works. Then his team lead asks for one more endpoint, GET /products/featured, for the home page banner. Rahul adds it at the bottom of the file, restarts the server and calls it. The answer is:

GET /products/featured -> 404 {"error":"Product not found"}

The route is right there in the file, spelled correctly. So why is Express sending the request to the wrong handler, and where did "Product not found" come from? The short answer is that Express checks routes in the order you register them, and his older /products/:id route happily accepted featured as an ID. This post explains that rule and everything around it: what Express is and why it exists, routes, req and res, route and query parameters, express.Router, controllers, middleware and next(), and the full journey of a request from the click of a button to the JSON on the screen. All examples use Express 5, the current major version, and every output below comes from a real run.

What Express Is and Why It Exists

Express is a small web framework for Node.js. A framework is ready-made code that handles the repetitive parts of a job, so you write only the parts that are specific to your app. Express handles routing (which code runs for which URL and method), reading request bodies, sending JSON and organising shared checks such as login into reusable functions called middleware.

Think of a restaurant that has a kitchen, tables and food but no waiters, cashier or manager. Every customer has to walk into the kitchen, find a cook, place the order and carry the plate out. The food is fine; the process is chaos. Node.js on its own is the kitchen: it can run a server, but you have to manage every request by hand. Express is the manager who receives each customer, sends the order to the right station and makes sure a plate goes back.

In the Node.js HTTP Module post we built a product CRUD API with only the built-in http module. It needed a URL parser, a regular expression for /products/:id, if (req.method === ...) chains, a stream reader for JSON bodies with size limits, a sendJson helper and one big try/catch. Here is the same idea in Express:

const express = require('express');
const app = express();
app.use(express.json({ limit: '10kb' })); // reads and parses JSON bodies

const products = [
  { id: 1, name: 'Basmati Rice 5 kg', price: 649 },
  { id: 2, name: 'Toned Milk 1 L', price: 56 },
];
let nextId = 3;

app.get('/products', (req, res) => {
  res.json(products);
});

app.get('/products/:id', (req, res) => {
  const product = products.find((p) => p.id === Number(req.params.id));
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
});

app.post('/products', (req, res) => {
  const { name, price } = req.body;
  const product = { id: nextId++, name, price };
  products.push(product);
  res.status(201).json(product);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

// GET  /products        -> 200 [{"id":1,"name":"Basmati Rice 5 kg","price":649},{"id":2,...}]
// GET  /products/2      -> 200 {"id":2,"name":"Toned Milk 1 L","price":56}
// POST /products {"name":"Toor Dal 1 kg","price":189}
//                       -> 201 {"id":3,"name":"Toor Dal 1 kg","price":189}

Express does not replace the http module; it sits on top of it. express() returns a request-handler function, app.listen() passes that function to http.createServer() and returns the ordinary Node.js server (we checked: typeof app is 'function' and the listen result is an http.Server). The req and res objects are the same Node.js objects with extra helpers such as req.params, req.query and res.json() added. For the wider picture of clients, servers and REST, see Backend Development Explained.

Why do so many Node.js teams pick Express? It is small and easy to learn, it does not force a folder structure on you, and its middleware model has a large ecosystem of ready-made packages (CORS, rate limiting, file uploads, logging). It is a common choice for REST APIs behind e-commerce sites, SaaS products and internal tools. It is not the only option; Fastify, Koa, Hono and NestJS solve the same problem with different trade-offs, but the ideas in this post carry over to all of them.

Installing Express and Your First Server

Create a project folder, initialise it and install Express. Express 5 needs Node.js 18 or later; we tested everything here with Express 5.3.0 on Node.js v24.

mkdir store-api && cd store-api
npm init -y
npm install express

Then create a file called server.js in the same folder with this code:

const express = require('express'); // load the Express package
const app = express();              // create the application

app.get('/', (req, res) => {
  res.send('Welcome to the store');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// $ node server.js
// Server running on http://localhost:3000
// GET / -> 200 text/html; charset=utf-8  "Welcome to the store"

Three lines do the work. require('express') loads the package. express() creates the application, the object you attach routes and middleware to (the restaurant itself). app.listen(3000) starts the server and keeps the process running, waiting for requests. Forgetting app.listen() is a classic first mistake: the script runs, prints nothing and exits, because nothing is keeping it alive. Press Ctrl+C to stop the server, and restart it after every code change (or run node --watch server.js, which restarts it for you).

What Is a Port?

Your computer has one IP address but thousands of ports. Think of the IP address as an apartment building and the port as the flat number: a visitor needs both to reach the right door. localhost:3000 means "this computer, flat 3000". Only one program can listen on a port at a time, so starting a second server on 3000 fails with EADDRINUSE. Ports 3000, 5000 and 8080 are popular for local development by convention only. In production the hosting platform usually decides the port, so read it from the environment: const port = Number(process.env.PORT) || 3000;. The HTTP module post has a table of common ports.

Routes: Matching a Method and a Path

A route tells Express "when a request with this method arrives for this path, run this function". Routes are like road signs in a city: without them every request would arrive and have nowhere to go. Each route has four parts:

app.get('/products', (req, res) => {
  res.send('Products');
});
// app         the Express application
// get         the HTTP method this route answers
// '/products' the path
// (req, res)  the handler: the code that runs when both match

There is one method per HTTP verb, and each one means something different to clients and tools:

Express methodHTTP methodTypical useExample
app.get()GETRead dataGET /products
app.post()POSTCreate somethingPOST /products
app.put()PUTReplace a whole recordPUT /products/7
app.patch()PATCHChange some fieldsPATCH /products/7
app.delete()DELETERemove a recordDELETE /products/7
app.all()AnyRun for every method on one pathapp.all('/health', ...)

GET /products and POST /products share a URL but are two different routes, which is exactly what the if (req.method === ...) chains in the raw http version did by hand. Express also ignores the query string when matching, so /products?page=2 still reaches the /products route; the plain req.url === '/products' check in the HTTP module post returned 404 for it.

req and res: the Request and the Reply

Every handler receives two objects. req is what the client sent, like an order slip. res is how you answer, like the plate that goes back. Express adds many helpers to both. These are the ones you will use almost every day:

req propertyWhat it holdsExample for GET /products/7?sort=price
req.methodThe HTTP method'GET'
req.paramsValues from :name parts of the path{ id: '7' }
req.queryValues from the query string{ sort: 'price' }
req.bodyThe parsed request body, only if a body parser ranundefined for a GET
req.headers, req.get(name)Request headers (names are lowercase; get is case-insensitive)req.get('user-agent')
req.path, req.originalUrlThe path without the query; the full original URL'/products/7', '/products/7?sort=price'
req.ip, req.hostnameClient address and the host name'::1', 'localhost'
res methodWhat it does
res.status(201)Sets the status code and returns res, so you can chain: res.status(201).json(data)
res.json(data)Converts data to JSON, sets Content-Type: application/json; charset=utf-8 and sends it
res.send(body)Sends a string (as text/html), a Buffer, or an object (as JSON)
res.sendStatus(204)Sends just a status; for 204 the body is empty
res.set(name, value)Sets a response header
res.redirect(301, '/products')Sends a redirect with a Location header

The rule from the raw http module still applies: each request gets exactly one response. res.json(), res.send(), res.sendStatus() and res.redirect() all finish the response, so call only one of them per request and return right after it when there is more code below.

Sending JSON

Most APIs return JSON because every client (React, Angular, Android, iOS, another server) can read it. res.json() does the JSON.stringify, the header and the Content-Type for you, which replaces the whole sendJson helper from the HTTP module post:

app.get('/products', (req, res) => {
  res.json(products);
});
// 200 application/json; charset=utf-8
// [{"id":1,"name":"Basmati Rice 5 kg","price":649},{"id":2,"name":"Toned Milk 1 L","price":56}]

Returning plain text such as res.send('Product Created') from an API is a common beginner habit. Front-end code then has to guess what happened. Send a status code plus JSON (res.status(201).json(product)), so the client can read the new record and its ID.

POST Requests and express.json()

A POST usually carries a JSON body. In Node.js the body is a stream that arrives in chunks, and nobody parses it automatically. Express does not parse it either until you add a body parser. Without one, req.body is undefined:

// No body parser registered
app.post('/products', (req, res) => {
  console.log(req.body); // undefined
  const { name, price } = req.body;
  // TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined.
});

The fix is one line, registered before your routes: app.use(express.json()). It reads the stream, checks the Content-Type, enforces a size limit (100 KB by default) and puts the parsed object in req.body. In Express 5 it only sets req.body when the request really is JSON: if a client forgets the Content-Type: application/json header, req.body stays undefined and the same TypeError appears, even with express.json() in place. (Express 4 used to give you an empty {} instead.) That is why the validation code later in this post reads req.body ?? {}. We tested what express.json({ limit: '1kb' }) does with bad input:

// POST '{"name": "Sugar", price: 45}'   (price has no quotes: invalid JSON)
// -> 400 {"error":"Expected double-quoted property name in JSON at position 18 (line 1 column 19)"}
// POST a 2 KB body with a 1 KB limit
// -> 413 {"error":"request entity too large"}
// POST '{"name":"Sugar","price":45}'
// -> 200 {"name":"Sugar","price":45}

These errors were turned into JSON by the small error handler shown later; Express's built-in handler sends the same status codes as an HTML page. That is the 400/413 work from the hand-written readJson helper, done for you.

Route Parameters vs Query Parameters

A route parameter is a named part of the path, written with a colon. It identifies which resource you want. Express collects them in req.params:

app.get('/products/:id', (req, res) => {
  res.json(req.params);
});
// GET /products/101 -> {"id":"101"}

app.get('/sellers/:sellerId/products/:productId', (req, res) => {
  res.json(req.params);
});
// GET /sellers/12/products/100 -> {"sellerId":"12","productId":"100"}

A query parameter comes after the ? and describes how you want a list: search, filter, sort, page. Express parses them into req.query:

app.get('/search', (req, res) => {
  res.json(req.query);
});
// GET /search?q=rice&page=1&limit=20  -> {"q":"rice","page":"1","limit":"20"}
// GET /search?tag=rice&tag=organic    -> {"tag":["rice","organic"]}
// GET /search?price[lte]=500          -> {"price[lte]":"500"}

Notice that every value is a string: "101", not 101. Compare p.id === req.params.id with a numeric ID and you get no match, which is why the code above uses Number(req.params.id). A repeated key becomes an array, so code that expects a string can break when someone sends ?tag=a&tag=b. And Express 5 uses the "simple" query parser by default, so bracket syntax like price[lte]=500 is no longer turned into a nested object as it was in Express 4. Always convert and validate query values before using them.

Route parameterQuery parameter
Looks like/products/101/products?category=grocery&page=2
Read withreq.params.idreq.query.category
PurposeIdentify one specific resourceFilter, search, sort, paginate a list
Required?Yes, part of the route; a missing part means a different routeOptional; missing keys are undefined
Value typeStringString, or an array of strings if repeated
ExampleGET /orders/5521GET /products?search=rice

Express 5 Path Syntax Changes

Express 5 uses a newer version of the path-to-regexp library, and some patterns from older tutorials now throw an error when the route is registered, so the server does not even start. We tried them:

app.get('*', handler);
// PathError: Missing parameter name at index 1: *; visit https://git.new/pathToRegexpError for info
app.all('*', handler);
// PathError: Missing parameter name at index 1: *; ...
app.get('/products/:id?', handler);
// PathError: Unexpected ? at index 13: /products/:id?; ...

// Express 5 versions
app.get('/files/*splat', (req, res) => res.json(req.params));
// GET /files/invoices/2026/oct.pdf -> {"splat":["invoices","2026","oct.pdf"]}

app.get('/products{/:format}', (req, res) => res.json({ format: req.params.format ?? 'none' }));
// GET /products     -> {"format":"none"}
// GET /products/csv -> {"format":"csv"}

A wildcard now needs a name (*splat), and it collects the matched segments as an array. Optional parts are written in braces ({/:format}) instead of with a trailing ?. If you copy a tutorial that uses app.all('*', ...) for a 404 page and the server refuses to start, this is why. The 404 section below shows the Express 5 way.

Why Route Order Matters

Express keeps routes and middleware in a list, in the order you register them. For each request it walks down the list and runs the first matching handler. If that handler sends a response, the search stops. It does not pick the "best" or "most specific" match. Here is Rahul's code from the opening:

app.get('/products/:id', (req, res) => {
  const product = products.find((p) => p.id === Number(req.params.id));
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
});

app.get('/products/featured', (req, res) => {   // never reached
  res.json(products.filter((p) => p.featured));
});

// GET /products/2        -> 200 {"id":2,"name":"Toned Milk 1 L",...}
// GET /products/featured -> 404 {"error":"Product not found"}

:id matches any single path segment, including the word featured. So Express runs the first handler with req.params.id === 'featured', Number('featured') is NaN, no product has that ID, and the handler answers 404. The /featured route never gets a chance.

Rahul's fix: he moves app.get('/products/featured', ...) above /products/:id. The rule to remember is fixed paths first, parameter paths after. With the order swapped, GET /products/featured returns 200 with the featured list and GET /products/2 still works. Another safe habit is to reject non-numeric IDs inside the :id handler with a 400, so a wrong route shows up as an obvious "invalid ID" error instead of a misleading "not found".

Handling 404: Routes That Don't Exist

If no route matches, Express's built-in fallback replies with an HTML page that says Cannot GET /orders. For a JSON API you want a JSON answer instead. Add a middleware with app.use() after all your routes: it only runs when nothing above it responded.

// ... all routes above ...

app.use((req, res) => {
  res.status(404).json({ error: `Route ${req.method} ${req.originalUrl} not found` });
});

// GET /orders -> 404 {"error":"Route GET /orders not found"}

Use app.use() rather than app.all('*', ...), which throws in Express 5 as shown above. Placement matters: put this 404 handler at the top of the file and every request gets a 404, because it matches everything and never calls next().

express.Router: Splitting Routes into Files

Five routes in server.js are fine. A real store has products, orders, users, payments, deliveries and notifications, each with several routes, and soon the file holds 80 or more route definitions next to each other. Finding anything becomes slow and two people editing the same file causes merge conflicts. express.Router() solves this. A router is a mini application: it has its own get, post and use, and you mount it on a path prefix.

// src/routes/productRoutes.js
const express = require('express');
const { getProducts, getFeatured, getProduct } = require('../controllers/productController');

const router = express.Router();

router.get('/', getProducts);          // GET /api/v1/products
router.get('/featured', getFeatured);  // GET /api/v1/products/featured (before /:id)
router.get('/:id', getProduct);        // GET /api/v1/products/42

module.exports = router;

// src/app.js
const productRoutes = require('./routes/productRoutes');
app.use('/api/v1/products', productRoutes);

Inside the router, paths are written relative to the mount point: router.get('/') becomes /api/v1/products, and router.get('/:id') becomes /api/v1/products/:id. The route-order rule applies inside a router too, which is why /featured sits above /:id. Inside the router, req.originalUrl still holds the full URL, while req.url and req.path are relative to the mount point.

Controllers: Keeping Route Files Short

A route file should read like a list of endpoints. The code that handles each one moves into a controller: a function that reads req, calls the code that does the real work, and sends res.

// src/controllers/productController.js
const productService = require('../services/productService');

exports.getProducts = async (req, res) => {
  res.json(await productService.list());
};

exports.getFeatured = async (req, res) => {
  res.json(await productService.featured());
};

exports.getProduct = async (req, res) => {
  const product = await productService.findById(Number(req.params.id));
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
};

The original version of this post said controllers contain the business logic. In small apps they often do, but as an app grows it pays to go one step further: controllers handle HTTP (read input, choose a status code), and services hold the business rules (check stock, calculate the total, apply a discount). A service knows nothing about req or res, so the same logic can be reused from a cron job or a queue worker and tested without starting a server. The Node.js Backend Architecture post builds on this structure with API security, rate limiting and Redis caching.

A Project Structure That Scales

Here is a layout for a small-to-medium Express API. Folder names vary between teams, but each folder has one clear job:

store-api/
├── src/
│   ├── routes/            # URL + method -> controller, nothing else
│   │   ├── productRoutes.js
│   │   ├── orderRoutes.js
│   │   └── userRoutes.js
│   ├── controllers/       # read req, call a service, send res
│   ├── services/          # business rules: stock, pricing, GST, orders
│   ├── models/            # database queries
│   ├── middlewares/       # code that runs before controllers
│   │   ├── auth.js
│   │   ├── validateOrder.js
│   │   ├── logger.js
│   │   └── errorHandler.js
│   ├── config/            # settings read from process.env
│   ├── app.js             # builds the app: middleware, routers, 404, errors
│   └── server.js          # app.listen(port)
├── tests/
├── .env                   # local secrets, never committed
└── package.json

Keeping app.js (build the app) separate from server.js (start listening) means a test can import the app, listen on any port, call it with fetch and close it. That is exactly how every sample in this post was tested.

Naming Routes: Nouns, Plurals and Versions

Good route names make an API predictable, so a front-end developer can guess an endpoint before reading the documentation. Three conventions cover most cases:

  • Use nouns, not verbs. The HTTP method is already the verb. Write GET /products and POST /orders, not /getProducts or /createOrder, and avoid vague names like /getStuff.
  • Use plural names consistently. /products for the list and /products/:id for one item. Mixing /product and /orders forces people to remember which is which.
  • Version the API. Prefix routes with /api/v1. When you need a breaking change, add /api/v2 alongside it, and old mobile app versions that users have not updated keep working on v1.

Put together, a store's route design looks like this. Nested routes such as /sellers/:sellerId/products express "products belonging to this seller":

GET    /api/v1/products              list products (?search=, ?category=, ?page=)
GET    /api/v1/products/featured     featured products (declared before /:id)
GET    /api/v1/products/:id          one product
POST   /api/v1/products              create a product
PUT    /api/v1/products/:id          replace a product
DELETE /api/v1/products/:id          delete a product

GET    /api/v1/orders                the logged-in user's orders
GET    /api/v1/orders/:id            one order
POST   /api/v1/orders                place an order

GET    /api/v1/sellers/:sellerId/products   one seller's products
POST   /api/v1/payments                     start a payment
GET    /api/v1/payments/:id                 payment status

Middleware: Code That Runs Between Request and Response

Think of the security desk at the entrance of an office building. Before anyone reaches a department, the guard checks the ID card, writes the name in the visitor register and decides: let the person through, or turn them away. Middleware is that guard. It is a function that runs between the request arriving and the final response, and it can read or change req, end the request early with a response, or pass it on.

Why does this matter? Suppose 40 of your routes need a logged-in user. Without middleware you would paste the same token check into 40 handlers, and a fix to that check would need 40 edits. With middleware you write it once and attach it where it is needed. Logging, authentication, validation, body parsing, CORS and rate limiting are all middleware.

The (req, res, next) Signature

A middleware function takes three arguments. The first two are the same req and res as in a route handler. The third, next, is a function Express gives you to say "I'm done, move on to the next function in the list". Every middleware must do one of two things:

  • Call next() to pass the request on (the guard lets the visitor through), or
  • Send a response, such as return res.status(401).json(...), which ends the request there (the guard turns the visitor away).
const logger = (req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`[log] ${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`);
  });
  next();
};

app.use(logger);
// [log] GET /products 200 8ms
// [log] POST /products 401 1ms   (timings will differ on your machine)

This logger waits for the response's finish event, so it can record the final status code and how long the request took, not just that it arrived. Note also that a route handler is really just middleware that does not call next; Express treats both the same way.

app.use, Global and Route-Specific Middleware

app.use(fn) registers middleware for every request, whatever the method or path. That is global middleware, right for logging and body parsing. app.use('/api', fn) limits it to paths that start with /api. For checks that only some routes need, pass the middleware directly in the route, before the handler. You can pass as many as you like, and they run left to right:

app.use(logger);           // global: every request
app.use(express.json());   // global: parse JSON bodies

app.get('/products', getProducts);                          // public
app.post('/products', auth, validateProduct, createProduct); // login + valid body first

Here anyone can list products, but creating one requires a login and a valid body. A router can also have its own middleware: router.use(auth) at the top of orderRoutes.js protects every order route in one line.

Authentication, Validation and Logging Examples

Here are the two middleware functions used for POST /products above. The authentication one checks the Authorization header and attaches the user to req so later functions can use it. In a real app it would verify a JWT; the Authentication, Authorization & JWT post builds that part properly.

const auth = (req, res, next) => {
  const header = req.get('authorization') || '';
  if (!header.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Login required' });
  }
  req.user = { id: 7, role: 'seller' }; // a real app verifies a JWT here
  next();
};

const validateProduct = (req, res, next) => {
  const { name, price } = req.body ?? {};
  if (typeof name !== 'string' || name.trim() === '') {
    return res.status(400).json({ error: 'name is required' });
  }
  if (typeof price !== 'number' || !(price > 0)) {
    return res.status(400).json({ error: 'price must be a positive number' });
  }
  next();
};

app.post('/products', auth, validateProduct, (req, res) => {
  res.status(201).json({ id: 3, ...req.body, sellerId: req.user.id });
});

// POST /products (no token)                     -> 401 {"error":"Login required"}
// POST /products {"name":"","price":-10} + token -> 400 {"error":"name is required"}
// POST /products {"name":"Toor Dal 1 kg","price":189} + token
//                                               -> 201 {"id":3,"name":"Toor Dal 1 kg","price":189,"sellerId":7}

Validation middleware stops bad data (empty names, negative prices, invalid emails or phone numbers) before it reaches your database, and every rejected request gets a clear 400 explaining why. Notice the return before each res.status(...): without it, the function would carry on and call next() after already responding. The !(price > 0) form also rejects NaN. Real projects often use a schema library such as Zod or Joi for this, but the shape is the same.

Execution Order

Middleware runs in the order it is registered, top to bottom, and within one route from left to right:

app.get('/order-demo',
  (req, res, next) => { console.log('1. first'); next(); },
  (req, res, next) => { console.log('2. second'); next(); },
  (req, res) => { console.log('3. handler'); res.send('done'); }
);
// 1. first
// 2. second
// 3. handler

Order changes behaviour, sometimes silently. If app.use(express.json()) is registered after a route, that route sees req.body as undefined. If a logger is registered below some routes, it never sees requests those routes answer. We tested this: with the logger placed between /products and /orders, a request to /orders was logged but a request to /products was not. A safe order for app.js is: logger, security headers and CORS, body parsers, routers, 404 handler, error handler.

Forgetting next(), and Sending Twice

A few weeks later Rahul adds a stock-check middleware in front of a new /stock endpoint. He writes the log line, tests nothing else, and ships it:

const checkStock = (req, res, next) => {
  console.log('checking stock...');
  // forgot next()
};
app.get('/stock', checkStock, (req, res) => res.json({ inStock: true }));

// checking stock...
// (the client waits; our test's fetch gave up after 2 seconds)
// TimeoutError: The operation was aborted due to timeout

Nothing crashes and no error is logged; the request just hangs. Express is waiting for checkStock to either respond or call next(), and it does neither. The browser shows a spinner until it gives up, and the open connection uses server resources the whole time. When a request hangs with no error, the first thing to check is a middleware path that neither responds nor calls next(), including an if branch that forgets to. Rahul adds next() as the last line and the route answers instantly.

The opposite mistake is responding and calling next(), so a second function tries to respond again:

app.get('/twice', (req, res, next) => {
  res.json({ ok: true });
  next();                    // should not be here
}, (req, res) => {
  res.json({ ok: 'again' }); // second response
});

// Client gets: 200 {"ok":true}
// Server logs: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

The client gets the first response; the second throws. The same error appears when an if block responds but forgets to return, so code below it responds too. The rule is simple: respond or call next(), never both, and write return res.... whenever more code follows.

Built-in Middleware

Express 5 ships with five middleware functions, all based on the body-parser and serve-static packages. Everything else (CORS, cookies, rate limiting, file uploads, security headers) comes from separate npm packages.

MiddlewareWhat it doesExample
express.json()Parses application/json bodies into req.body (default limit 100 KB){"name":"Sugar","price":45}
express.urlencoded()Parses HTML form posts (application/x-www-form-urlencoded); Express 5 defaults to extended: falsename=Rahul&city=Nashik becomes {"name":"Rahul","city":"Nashik"}
express.static('public')Serves files from a folder: images, CSS, a built React appGET /style.css returns 200 text/css
express.text()Reads text/plain bodies as a stringUseful for simple webhooks
express.raw()Reads the body as a BufferNeeded when verifying payment-gateway webhook signatures over the exact bytes

Error-Handling Middleware (and Express 5's Async Fix)

An error-handling middleware has four arguments, (err, req, res, next), and Express only calls it when something has failed: a handler threw, or code called next(err). Register it last, after the 404 handler. The most useful Express 5 change for beginners is that if an async handler throws or returns a rejected promise, Express now passes the error to this handler automatically. In Express 4 nobody caught that rejected promise: the client never got a response, and on Node.js 15 and later the unhandled rejection crashes the whole process by default, unless you wrapped every handler in try/catch or used a helper package.

app.get('/boom', async (req, res) => {
  throw new Error('Database unavailable'); // e.g. a failed query
});

app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status === 500) console.error('Logged:', err.message);
  res.status(status).json({ error: status === 500 ? 'Internal Server Error' : err.message });
});

// Logged: Database unavailable
// GET /boom -> 500 {"error":"Internal Server Error"}

The handler logs real bugs on the server and shows clients only a generic message, so stack traces and database details never leak. Errors from express.json() carry their own status (400 or 413), which is how the invalid-JSON test earlier got a 400. That is enough to start with. Custom error classes, logging to files and services, and file-upload errors are covered in Node.js Error Handling, Logging & File Upload.

The Request and Response Lifecycle

To a shopper, placing an order is one click and a "Order placed" message a moment later. Behind that click a request passes through many layers, and knowing them is what lets you debug quickly. The journey, merged into one flow, looks like this:

  1. The user acts. The front end collects data such as {"productId": 1, "quantity": 5}.
  2. The request is built. POST /api/v1/orders with headers Authorization: Bearer <token> and Content-Type: application/json, plus the JSON body.
  3. It travels over the internet. DNS finds the server's IP address, and the request passes through the mobile network or ISP and routers (covered in Backend Development Explained).
  4. Node.js receives it, and Express starts walking its list. Global middleware runs first: logger, then express.json().
  5. The matching router and its middleware run. Authentication (401 if the token is bad), then validation (400 if the body is wrong).
  6. The controller runs and calls the service, which applies business rules (does the product exist, is there enough stock, what is the total).
  7. The database is read and written through the model layer, and the result comes back.
  8. The controller sends the response, for example res.status(201).json(order).
  9. The response travels back the same way, and the front end updates the screen.
Client logger + express.json auth validation controller service + DB res.json 201 POST /api/v1/orders: each step calls next() or responds 401 400 404 / 409 / 500 Response travels back; red exits end the request early with an error status

Here is that flow as runnable code, using the project structure from earlier. The service is where the business rules live, and it throws an error with a status for expected failures:

// src/services/orderService.js
const productService = require('./productService');

class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

let nextOrder = 1001;

exports.create = async ({ productId, quantity }, user) => {
  const product = await productService.findById(productId);
  if (!product) throw new HttpError(404, `Product ${productId} not found`);
  if (product.stock < quantity) throw new HttpError(409, `Only ${product.stock} left in stock`);
  product.stock -= quantity;
  return { orderId: `ORD-${nextOrder++}`, productId, quantity, total: product.price * quantity, userId: user.id };
};

// src/controllers/orderController.js
const orderService = require('../services/orderService');

exports.createOrder = async (req, res) => {
  const order = await orderService.create(req.body, req.user);
  res.status(201).json(order);
};

// src/routes/orderRoutes.js
router.post('/', auth, validateOrder, createOrder); // POST /api/v1/orders

// src/app.js
app.use(logger);                              // 1. logger
app.use(express.json({ limit: '10kb' }));     // 2. body parser
app.use('/api/v1/products', productRoutes);   // 3. routers
app.use('/api/v1/orders', orderRoutes);
app.use(notFound);                            // 4. 404: no route matched
app.use(errorHandler);                        // 5. error handler (4 arguments)

The controller has no try/catch. When the service throws, Express 5 forwards the rejected promise to errorHandler, which uses err.status for expected errors and 500 for everything else. We imported app.js into a test script, listened on a spare port, and sent one request per scenario:

POST /orders {"productId":1,"quantity":5} + token
  [log] POST /api/v1/orders 201
  -> 201 {"orderId":"ORD-1001","productId":1,"quantity":5,"total":3245,"userId":7}

POST /orders (no token)                      -> 401 {"error":"Login required"}
POST /orders {"productId":1,"quantity":-10}  -> 400 {"error":"productId and a quantity of at least 1 are required"}
POST /orders {"productId":42,"quantity":1}   -> 404 {"error":"Product 42 not found"}
POST /orders {"productId":2,"quantity":1}    -> 409 {"error":"Only 0 left in stock"}
POST /orders (database down)
  [error] connect ECONNREFUSED 127.0.0.1:3306
  -> 500 {"error":"Internal Server Error"}
GET /payments                                -> 404 {"error":"Route GET /api/v1/payments not found"}

The total, 3245, is ₹649 × 5. For the database-down case the test service threw the same ECONNREFUSED error a MySQL driver raises when the database is not reachable.

Failure Scenarios at a Glance

What went wrongWhere it is caughtStatusDoes the request go further?
Missing or invalid tokenAuth middleware401 UnauthorizedNo; validation, controller and database never run
Logged in, but not allowed (a buyer trying a seller action)Authorization middleware403 ForbiddenNo
Invalid JSON, or a quantity of -10express.json() or validation middleware400 Bad RequestNo
Product does not existService, after a database lookup404 Not FoundStops at the service
Not enough stockService409 ConflictStops at the service
Database unavailable, or a bugError handler500 Internal Server ErrorStops; logged on the server
No such route404 middleware at the end404 Not FoundNothing matched

This also gives you a debugging checklist. When users report "orders are not being created", walk the lifecycle in order. Did the request reach the server (is there a log line)? Did authentication pass (check the token)? Did validation pass (check the payload)? Did the controller and service run? Did the database respond? What status went back? The logger that records method, URL, status and time answers the first and last questions immediately, which is why it should be the first middleware you add.

Express Interview Questions, Checked and Corrected

These are the questions from the original post, with short answers you can say aloud. Where the common answer is incomplete, the correction is noted.

1. What is Express.js? A small, unopinionated web framework for Node.js, used to build APIs and web apps. It adds routing, middleware, request-body parsing and response helpers on top of Node's http module.

2. Why use Express instead of the http module? It removes the repetitive work: URL and method matching, route parameters, query parsing, body parsing with limits, JSON responses and central error handling. A stronger answer adds that Express still runs on http, so knowing the raw module helps when debugging headers or streams.

3. What does app.listen() do? It creates an http.Server with the app as its request handler, starts listening on the port, and returns the server object (useful for server.close() in tests and graceful shutdown).

4. What is a route? A combination of an HTTP method and a path pattern, plus the handler(s) to run when a request matches both.

5. What is the difference between req and res? req holds what the client sent (method, URL, params, query, headers, body). res is how you reply (status, headers, body). Each request must get exactly one response.

6. What is routing? Deciding which code runs for an incoming request, based on its method and path.

7. What is express.Router? A mini application with its own routes and middleware that you mount on a path prefix with app.use('/api/v1/products', router). Paths inside it are relative to that prefix.

8. req.params vs req.query? req.params comes from named path segments (/products/101 gives { id: '101' }) and identifies a resource. req.query comes from the query string (?page=1) and filters or paginates. Both hold strings, so convert numbers yourself.

9. Why split routes into separate files? Readability (each feature's endpoints in one short file), fewer merge conflicts, and the ability to attach middleware per feature with router.use().

10. Why does route order matter? Express runs the first matching handler in registration order, not the most specific one. /products/:id registered before /products/featured swallows the word "featured" as an ID.

11. What is middleware, and why use it? A function with (req, res, next) that runs during the request, before the final handler, and either passes control on or ends the request. It keeps cross-cutting work such as logging, authentication, validation and body parsing in one place instead of repeating it in every route.

12. What happens if next() is not called? The usual answer, "the request stops", is incomplete. If the middleware also sends no response, the request hangs: the client waits until it gives up, and nothing is logged. If it did send a response, not calling next() is correct.

13. What is app.use()? It registers middleware (or a router) for all methods, optionally limited to a path prefix. It matches any path that starts with the prefix, unlike app.get('/x'), which matches the exact path.

14. What is the request-response lifecycle? The full journey of a request: client, network, Express, global middleware, router and route middleware, controller, service and database, response, back to the client.

15. What executes first? The original answer was "middleware". More precisely: whatever was registered first. Middleware registered with app.use() after a route does not run for requests that route answers.

16. Where does business logic live? The original answer said controllers. In a layered app, the controller deals with HTTP and the business rules live in a service layer, which can be tested and reused without Express.

17. When is the database accessed? Only after the request has passed authentication and validation and reached a controller and service, so bad or unauthorised requests never cost a database query.

18. What happens if middleware sends a response? The rest of the chain does not run, as long as the middleware does not also call next(). The JavaScript after res.json() in the same function still executes, though, which is why you write return res.status(401).json(...).

19. What changed in Express 5 that a beginner should know? Rejected promises from async handlers go to the error handler automatically; wildcards need a name (/*splat) and app.all('*') throws, so use app.use() for 404s; optional parameters use braces ({/:format}); the query parser is "simple" by default; and req.body is undefined unless a body parser handled the request.

Common Mistakes (and the Fix)

MistakeWhat happensFix
/products/:id registered above /products/featuredfeatured is treated as an ID: 404 "Product not found"Fixed paths first, parameter paths after
No express.json(), or the client omits Content-Type: application/jsonreq.body is undefined; destructuring throws a TypeError (500)Register express.json() before routes; send the header; read req.body ?? {}
Middleware that neither responds nor calls next()The request hangs with no error loggedEvery path ends in next() or return res...
Responding and then calling next(), or forgetting returnERR_HTTP_HEADERS_SENTreturn res.status(...).json(...)
app.all('*', ...) or :id? copied from an Express 4 tutorialServer fails to start with a PathErrorapp.use(notFound) for 404s; /*splat and {/:param}
Comparing req.params.id to a number with ===Never matches, because params are stringsNumber(req.params.id) and validate it

My Opinion

Start new projects on Express 5, not 4. The automatic handling of async errors alone removes a whole class of hanging requests and wrapper boilerplate. Most Express 4 tutorials still work once you fix the wildcard and optional-parameter syntax.

Make the logger the first middleware you write. One line per request with method, URL, status and time answers most "it doesn't work" questions in seconds, and it is the first step of the lifecycle debugging checklist.

Keep controllers thin from the start. Moving business rules into services costs a few extra files on day one and saves a painful refactor later, when the same rule is needed by a cron job or a second endpoint.

Treat return res... as a habit, not a fix. Writing return before every early response prevents both "headers already sent" and accidental fall-through, and it costs nothing.

Version and pluralise routes before the first client ships. Renaming /getProduct after a mobile app is in users' hands is far harder than starting with /api/v1/products.

Try It Yourself

Answer these first, then check. For questions 2, 3 and 6, run the code to confirm.

1. Write the routes (method + path) for a library API: list books, get one book,
   add a book, delete a book, and list the loans of one member.
2. What does GET /books/new return here, and how do you fix it?
   app.get('/books/:id', (req, res) => res.json({ id: req.params.id }));
   app.get('/books/new', (req, res) => res.json({ form: true }));
3. For GET /books?author=Premchand&page=2, what are req.query and typeof req.query.page?
4. A POST handler logs req.body as undefined even though express.json() is registered.
   Give two possible reasons.
5. Write a middleware that rejects any request without an x-api-key header
   with 401, and otherwise passes it on.
6. In Express 5, what happens when you register app.all('*', handler)?
   What should you use for a 404 handler instead?
7. Your logger is registered after app.use('/api/v1/books', bookRoutes).
   Which requests will it log?
8. An order request fails. List, in order, the layers you would check.
Show answers
1. GET /api/v1/books, GET /api/v1/books/:id, POST /api/v1/books,
   DELETE /api/v1/books/:id, GET /api/v1/members/:memberId/loans
2. {"id":"new"}, because /books/:id is checked first and matches "new".
   Move app.get('/books/new', ...) above /books/:id.
3. { author: 'Premchand', page: '2' } and 'string'.
4. (a) express.json() is registered after the route.
   (b) The client did not send Content-Type: application/json
       (Express 5 leaves req.body undefined in that case).
5. const requireKey = (req, res, next) => {
     if (!req.get('x-api-key')) return res.status(401).json({ error: 'API key required' });
     next();
   };
6. It throws PathError: Missing parameter name at index 1: *, so the server does
   not start. Use app.use((req, res) => res.status(404).json(...)) after all routes.
7. Only requests that bookRoutes did not answer (other paths, or book requests that
   fell through with next()). Move the logger to the top.
8. Did the request arrive (logs)? Did auth pass (token)? Did validation pass (body)?
   Did the controller and service run? Did the database respond? What status was sent?

Frequently Asked Questions

Should I learn Express 4 or Express 5?

Express 5. It is the version npm install express gives you today, and the core ideas (routes, req/res, middleware, routers) are the same as in Express 4. When you read older code, the differences you will meet most are the wildcard and optional-parameter syntax and the manual try/catch around async handlers, which Express 5 no longer needs.

Is middleware the same as a controller?

Technically both are functions Express calls with req and res. By convention, middleware does a shared job and calls next() (log, authenticate, validate), while the controller is the last function in the chain and sends the actual response for that endpoint.

Do I still need the cors package with Express?

Yes, if a browser front end on another origin calls your API. Express does not handle CORS by itself. The cors package is middleware that sets the Access-Control-Allow-* headers and answers the OPTIONS preflight, which the HTTP module post did by hand.

Can a route have more than one middleware?

Yes. app.post('/orders', auth, validateOrder, createOrder) runs them left to right. You can also pass an array, or attach middleware to a whole router with router.use().

Why does my server crash at start with "Missing parameter name"?

You are using an Express 4 path pattern, usually '*', in Express 5. Give the wildcard a name ('/*splat') or, for a catch-all 404, use app.use() without a path.

Key Takeaways

  • Express is a small framework on top of Node's http module; app.listen() creates a normal http.Server.
  • A route is a method plus a path; Express runs the first match in registration order, so put fixed paths like /products/featured before /products/:id.
  • req.params identifies a resource, req.query filters a list; both are strings.
  • req.body is undefined until express.json() (or another parser) handles the request, and that requires the right Content-Type.
  • Middleware is (req, res, next): respond or call next(), never both, never neither.
  • Split code into routers, controllers and services; version routes as /api/v1 with plural nouns.
  • End app.js with a 404 app.use() and a four-argument error handler; in Express 5, async errors reach it automatically.
  • Debug by walking the lifecycle: arrival, auth, validation, controller, database, response.

Next, protect these routes properly with Authentication, Authorization & JWT, or harden the API with rate limiting and caching in Node.js Backend Architecture.

References

Related Articles

Post a Comment

0 Comments