Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 43 ยท Routing

Routing Basics

Learn Express routing: app.get, post, put, patch and delete, app.all, how route order decides which handler runs, and how 404 fallthrough works, with runnable demos.

Routing decides which function answers a request. A route in Express is made of three parts: an HTTP method (GET, POST, and so on), a path (such as /books), and one or more handlers. When a request arrives, Express finds the first route whose method and path both match and runs its handler.

This lesson covers the route methods, app.all, how matching order works and what happens when nothing matches. The real Express snippets are read-only; the runnable examples use the mini Express stand-in.

One method per kind of action

HTTP methods describe intent. Express gives you one function per method:

JavaScript
app.get('/books', (req, res) => {
  res.json([{ id: 1, title: 'Dune' }]);
});

app.post('/books', (req, res) => {
  res.status(201).json({ created: true });
});

app.put('/books/:id', (req, res) => {
  res.json({ replaced: req.params.id });
});

app.patch('/books/:id', (req, res) => {
  res.json({ updated: req.params.id });
});

app.delete('/books/:id', (req, res) => {
  res.status(204).end();
});

Methods and their meaning

GET Read data. Never change anything.
POST Create something new.
PUT Replace a whole item.
PATCH Change part of an item.
1 / 2

A path alone is not enough: GET /books and POST /books are two different routes and can have two different handlers. If a client uses a method that has no route for that path, Express treats it as unmatched, even when the path exists for another method. (Some APIs answer that case with 405 Method Not Allowed; you can add that yourself.)

Method names are lower case in the code (app.get) and upper case on the wire (GET). app.del from old Express versions is gone; use app.delete.

Handlers: request, response, next

A handler receives (req, res, next). Use req to read the request and res to answer. Call next() only when you want to pass control to the following matching route or middleware. If you never respond and never call next, the client waits forever.

JavaScript
app.get('/ping', (req, res) => {
  res.send('pong');
});

You can also give a route several handlers; they run in order, each deciding whether to continue:

JavaScript
function checkKey(req, res, next) {
  if (req.get('x-api-key') !== 'secret') {
    return res.status(401).json({ error: 'Missing key' });
  }
  next();
}

app.get('/private', checkKey, (req, res) => {
  res.send('Welcome in');
});

Notice return res.status(401).... The return stops the function so that next() below is not reached. Forgetting it is a very common bug. This chain idea is the topic of How Middleware Works.

Route order matters

Express checks routes in the order you register them and stops at the first one that responds. So put specific routes before general ones.

Node.js Specific before general

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If /books/:id came first, GET /books/new would run it with id set to "new". This is a classic mistake: parameter routes act like wildcards for one path segment.

app.all: every method

app.all(path, handler) matches the path for any method. It is handy for catching unsupported methods or for shared checks on one path:

JavaScript
app.all('/secret', (req, res) => {
  res.status(403).send(`No ${req.method} for you`);
});

Do not confuse app.all with app.use. app.all needs a path match of the whole path; app.use is meant for middleware and matches path prefixes. See middleware.

The 404 fallthrough

When no route responds, Express runs its built-in final handler: status 404 and the text Cannot GET /something. That text is plain and not great for an API, so most apps add their own catch-all at the end, after every route:

JavaScript
app.use((req, res) => {
  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
});

Because it is registered last, it only runs when nothing before it answered. Putting it first would answer everything with 404; order is everything in Express.

Node.js Methods, app.all and a custom 404

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output: the second DELETE finds nothing and returns the handler's own 404 (a route-level 404, different from the catch-all), while /shelf reaches the catch-all.

Trailing slashes and case

By default Express treats /books and /BOOKS as the same route (case-insensitive) and also accepts /books/ with a trailing slash. You can turn that off with app.set('case sensitive routing', true) and app.set('strict routing', true). The stand-in accepts an optional trailing slash and is case sensitive; this is one of its simplifications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two routes match GET /books/new, and the first one sends a response without calling next(). Which handler's output does the client get?

    Express runs matching routes in registration order. When one responds and does not call next(), the rest are skipped.
  2. 2. Why should app.get('/books/new') come before app.get('/books/:id')?

    A parameter matches any single segment, so a later specific route would never be reached.
  3. 3. Where should a custom 404 handler go?

    It must be last so that it only runs when no earlier route responded.
  4. 4. What does app.all('/x', handler) match?

    app.all registers the handler for all HTTP methods on that path.
  5. 5. A client sends PATCH /books, but only GET and POST routes exist for /books. What happens by default?

    Method and path must both match. Without a match, the request reaches the 404 fallback.

Summary

  • Use app.get, post, put, patch and delete to attach handlers to a method and path.
  • Handlers take (req, res, next); respond once or call next(); use return after early replies.
  • Routes run in registration order, so register specific paths before parameter paths.
  • app.all matches every method for a path.
  • Add a catch-all 404 handler after all routes.

Next: Route Parameters and Query Strings.