Routing in Express — Node.js

A route = method + path + handler (the function that answers). Express checks routes from the top, and the first match answers. app.get("/notes/:id", ...)…

Note number 2 is clearly in the array, yet GET /notes/2 keeps getting a 404. The code looks right, and the terminal shows no error at all. The cause is small, and it is in how Express fills req.params.

Routing is how Express picks which code answers a request, based on its method and its path. Express reads your list of routes from the top and uses the first one that matches. If nothing matches, Express answers 404 right away, without running your code.

Route = method + path + handler

Our notes-api project now has two routes:

const express = require("express");
const app = express();

const notes = [
  { id: 1, title: "Groceries", content: "buy 5 kg of rice" },
  { id: 2, title: "Study", content: "Node.js chapter" },
];

// Every note, can be filtered with ?search=
app.get("/notes", (req, res) => {
  const { search } = req.query;
  if (!search) return res.json(notes);
  const results = notes.filter((n) => n.title.toLowerCase().includes(search.toLowerCase()));
  res.json(results);
});

// One note by its id
app.get("/notes/:id", (req, res) => {
  const item = notes.find((n) => n.id === Number(req.params.id));
  if (!item) {
    return res.status(404).json({ error: "Note not found" });
  }
  res.json(item);
});

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

Path parameter: req.params

:id in the path is a path parameter, which the previous lesson called a route parameter. A path parameter is a blank that the URL fills in. The one route /notes/:id serves /notes/1, /notes/2, all the way to /notes/999.

Request Route that matches req.params Answer
GET /notes/2 /notes/:id { id: "2" } {"id":2,"title":"Study","content":"Node.js chapter"}
GET /notes/2?sort=title /notes/:id { id: "2" } the same
GET /notes/9 /notes/:id { id: "9" } 404 {"error":"Note not found"}

What's in req.params is always text, because a URL is text. The part after ? isn't part of the path, so it doesn't go into the params. That's why GET /notes/2?sort=title still fills req.params.id with the text "2".

Text isn't equal to a number: "2" === 2 is false. So the route above writes Number(req.params.id) before comparing it with n.id, which is a number.

Query string: req.query

The part after ? is the query string: key=value pairs separated by &. Express puts it in req.query. In the /notes route, if (!search) return res.json(notes); sends every note when search isn't given. When it is given, filter keeps the notes whose title contains that text, ignoring letter case. So curl "http://localhost:3000/notes?search=stu" prints [{"id":2,"title":"Study","content":"Node.js chapter"}].

When no route matches

curl -i http://localhost:3000/hello gets HTTP/1.1 404 Not Found. The content is Express's small built-in HTML page: <pre>Cannot GET /hello</pre>. The method is matched too. POST /notes/2 gets Cannot POST /notes/2, because we only have a GET route for that path. Tell it apart from our own 404, {"error":"Note not found"}: for that 404, the route matched, but the data isn't there.

Two things make no difference when Express matches a path: letter case (/Notes/2 still matches) and a slash at the end (/notes/2/ still matches).

One resource, five routes

A resource is one kind of data that the API manages, here notes. Almost every API uses this pattern of routes, called REST:

Method Path For
GET /notes the list of all notes
GET /notes/:id one note
POST /notes create a new note
PUT /notes/:id change a note
DELETE /notes/:id delete a note

The path is a noun (/notes), and the method decides the action. We fill in the last three routes in the CRUD lesson.

express.Router: routes in their own file

As routes grow in number, move them to their own file with express.Router(). A router is a group of routes that you can attach to app:

// routes/notes.js
const express = require("express");
const router = express.Router();

router.get("/", (req, res) => { /* the list */ });
router.get("/:id", (req, res) => { /* one note */ });

module.exports = router;

// app.js
const notesRouter = require("./routes/notes");
app.use("/notes", notesRouter);

app.use("/notes", notesRouter) puts the prefix /notes in front of every route in that router. So router.get("/:id") serves GET /notes/:id, exactly as before.

📌 Express 5 differs from older tutorials

npm install express now installs Express 5. Many tutorials still use Express 4. Two path patterns from those tutorials stop Express 5 when the server starts. :id? means id may be missing, and * means any path:

Express 4 Express 5 When the old pattern is used in Express 5
/notes/:id? /notes{/:id} PathError [TypeError]: Unexpected ? at index 10: /notes/:id?; visit https://git.new/pathToRegexpError for info
* /*splat PathError [TypeError]: Missing parameter name at index 1: *; visit https://git.new/pathToRegexpError for info

In the exercise: a route with no server

The exercise doesn't run a server. The function findUser(id) plays the role of the handler of GET /users/:id: search the users array with find, then return the user, or null when there's none. find returns undefined when nothing matches, so write return users.find((u) => u.id === id) || null;. The starter's console.log lines print the result:

GET /users/2 -> {"id":2,"name":"Siti"}
GET /users/99 -> User not found

⚠️ Routes that miss

TL;DR: A route = method + path + handler (the function that answers). Express checks routes from the top, and the first match answers. app.get("/notes/:id", ...) fills req.params.id from the URL, always as text ("2", not 2). So convert it with Number() before comparing it with a number. The part after ? (the query string) goes to req.query, for example ?search=stu becomes { search: "stu" }, and takes no part in choosing the route. If no route matches, Express answers with a 404, such as Cannot GET /hello. REST, the pattern almost every API uses: GET/POST/PUT/DELETE to /notes and /notes/:id. express.Router() moves routes into their own file, and that router is attached with app.use("/notes", router). In Express 5, :id? (an id that may be missing) becomes {/:id}, and * (any path) becomes /*splat.

⚡ The first match answers

Write:

app.get("/notes/latest", (req, res) => { /* ... */ });
app.get("/notes/:id", (req, res) => { /* ... */ });
Guess first: if these two routes swap places, which one answers GET /notes/latest?

The :id route, with id = "latest". There is no note with that id, so the answer is a 404. Express uses the first route whose method and path match.

Meaning: A route = method + path + handler (the function that answers the request), and Express checks routes from the top. :id captures any part of the path. So put routes with a fixed path, such as /notes/latest, above the route with :id.

⚡ Params point, the query adjusts

Write:

const item = notes.find((n) => n.id === Number(req.params.id));
const { search } = req.query;

Meaning: notes is the array of data. /notes/2 fills req.params.id with "2", always text, so convert it with Number(). The part after ? goes to req.query: ?search=stu becomes { search: "stu" }, and takes no part in choosing the route. Params point at one piece of data, the query adjusts a list, for example a search.

⚡ Routes in their own file

Write:

const notesRouter = require("./routes/notes");
app.use("/notes", notesRouter);

Meaning: express.Router() makes a router, a group of routes written in their own file, here routes/notes.js. require takes the router from that file as notesRouter, then app.use attaches it with the prefix /notes, so router.get("/:id") serves GET /notes/:id.

What you will learn