SyntaxStudy
Sign Up
Express.js Route Parameters, Wildcards, and app.route()
Express.js Beginner 1 min read

Route Parameters, Wildcards, and app.route()

Express provides `app.route()` as a chainable shorthand when multiple HTTP methods share the same path. Instead of repeating the path string for GET, PUT, and DELETE, you write `app.route('/resource').get(...).put(...).delete(...)`, which reduces duplication and groups related handlers visually. Wildcard segments (`*`) match any characters in that position, while optional segments use the `?` modifier. Regular expressions give even finer control — `app.get(/^\/products\/\d+$/, handler)` matches only numeric IDs. However, string patterns cover most real-world needs without the readability cost of regex. The `router.param()` hook runs a callback whenever a named parameter is present in a route, making it ideal for loading a record by ID once and attaching it to `req` for downstream handlers to use without repeating the database query.
Example
const express = require('express');
const app     = express();
app.use(express.json());

// Chained route methods — DRY path definition
app.route('/articles/:id')
    .get((req, res) => {
        res.json({ id: req.params.id, title: 'Sample Article' });
    })
    .put((req, res) => {
        res.json({ id: req.params.id, updated: true });
    })
    .delete((req, res) => {
        res.status(204).send();
    });

// router.param — auto-load resource
const router = express.Router();

router.param('userId', async (req, res, next, id) => {
    try {
        // Simulate DB lookup
        const user = { id, name: 'Alice' }; // replace with real query
        if (!user) return res.status(404).json({ error: 'User not found' });
        req.user = user;
        next();
    } catch (err) {
        next(err);
    }
});

router.get('/users/:userId', (req, res) => {
    res.json(req.user); // already loaded by param hook
});

app.use('/api', router);
app.listen(3000);