Express Routing Basics

Learn method-based routing, route parameters, query parameters, and how to organize routes with express.Router.

🎯 Introduction

By the end of this article, you will be able to define GET, POST, PUT, and DELETE routes, read route and query parameters, and use express.Router to move routes into separate files for a clearer project structure.


🧱 What Is Routing?

Routing maps a URL and request method to a handler function. When a client requests /users, routing determines which code the server runs.

Think of a parcel sorting center: each parcel (request) is sent to a different shelf (handler) based on its address label (URL) and type (request method).


🛠 Four Common Request Methods

In REST-style APIs, different request methods represent different operations. Express provides a registration method for each:

app.js
import express from 'express';

const app = express();

app.get('/users', (req, res) => {
    res.send('Get the user list');
});

app.post('/users', (req, res) => {
    res.send('Create a user');
});

app.put('/users', (req, res) => {
    res.send('Update user information');
});

app.delete('/users', (req, res) => {
    res.send('Delete a user');
});

app.listen(3000);

Requests to the same URL with different methods reach different handlers, each with its own responsibility:

  • GET: Retrieve data. Navigating to a URL in the browser address bar sends a GET request.
  • POST: Create data, usually with a request body.
  • PUT: Update data.
  • DELETE: Delete data.
The browser address bar only sends GET requests. To test POST, PUT, or DELETE, use curl in your terminal or an API testing tool. We will cover these tools in a later article.

🛠 Route Parameters with req.params

An endpoint often needs to work with a particular record by ID: /users/1, for example, identifies user 1. Since IDs vary, defining a separate route for every user is impractical. Use route parameters instead:

app.js
app.get('/users/:id', (req, res) => {
    res.send(`User details: ${req.params.id}`);
});

The :id segment is a placeholder. Both /users/1 and /users/99 match this route, and req.params.id gives you the actual value.

The id value in req.params is a string. For /users/1, req.params.id is '1', not the number 1. Use Number() when you need it for numeric operations.

🛠 Query Parameters with req.query

The key-value pairs after the question mark in a URL are query parameters. They are commonly used for pagination and filtering, as in /users?page=2&size=10. Express parses them and exposes them through req.query:

app.js
app.get('/users', (req, res) => {
    const { page, size } = req.query;

    res.send(`Page ${page}, ${size} items per page`);
});

Visiting http://localhost:3000/users?page=2&size=10 returns “Page 2, 10 items per page”.

In Express 5, req.query is a read-only getter property. You can read it, but should not try to reassign it.

⚡ Route Parameters or Query Parameters?

Both carry data in the URL, but serve different purposes:

  • Route parameters: Identify a specific resource as part of the URL structure, such as /users/1.
  • Query parameters: Provide optional filters, such as ?page=2&keyword=Zhang.

Use a route parameter when the endpoint cannot identify its target without it. Use a query parameter when the endpoint can still work with a default value if it is omitted.


🛠 Organize Routes with express.Router

Keeping every route in app.js becomes difficult to maintain as the API grows. A Router is a small, self-contained routing object that lets you group related routes in a separate file:

routes/user.js
import { Router } from 'express';

const router = Router();

// Here, / corresponds to the mount path /users
router.get('/', (req, res) => {
    res.send('User list');
});

router.get('/:id', (req, res) => {
    res.send(`User details: ${req.params.id}`);
});

export default router;

Then mount it in the entry file:

app.js
import express from 'express';
import userRouter from './routes/user.js';

const app = express();

// Pass requests under /users to userRouter
app.use('/users', userRouter);

app.listen(3000);

Now requests to /users and /users/1 reach routes/user.js. To add article routes later, create routes/article.js and mount it at /articles. Each file handles its own resource.

ESM imports of local files must include the .js extension. Writing import userRouter from './routes/user' causes a module-not-found error, as discussed in the previous Node.js course.

💡 all vs. use

Besides registering routes for specific methods, there are two other forms worth recognizing:

  • app.all('/users', handler): Runs the handler for GET, POST, and every other request method.
  • app.use('/users', handler): Matches all methods on paths under /users. Commonly used to mount routers and middleware.

The key difference is that all matches the route path, while use matches a path prefix. In everyday development, method-specific registrations such as app.get and app.post are more common.


❓ Questions and Answers

Q1: Can I use route parameters and query parameters together?

Yes. In /users/1/comments?page=2, req.params.id provides the user ID and req.query.page provides the page number. They do not interfere with each other.

Q2: If I define both /users/:id and /users/new, which handles /users/new?

Express matches routes in registration order. Register /users/new before /users/:id; otherwise, new is treated as the id value.

Q3: How should I write paths in a separate Router file?

Write paths relative to the mount path. If the Router is mounted at /users, / in the Router means /users, and /:id means /users/:id. Do not repeat the full path inside the Router.

Q4: Can a GET request have a body?

A GET request body has no generally defined semantics. Use route or query parameters to pass data with GET. To submit data, use a method such as POST or PUT.


🧪 Exercise

Define routes for a books module in a separate file:

  1. Create routes/book.js with two routes: GET /books returns “Book list”, and GET /books/:id returns “Book details: the ID value”.
  2. Mount it at /books in app.js.
routes/book.js
// Write your code here
app.js
import express from 'express';

const app = express();

// Write your code here

app.listen(3000);

🎉 You now know the common Express routing patterns! Next, we will explore middleware, the mechanism at the heart of Express.