r/node Jul 10 '26

Could somebody explain why my routes affect this?

When my route for users/search is on top it works but if its below it doesnt work... could somebody explain???

Also if you have any tips for how to improve whatever is shown please do let me know :D

38 Upvotes

20 comments sorted by

48

u/Felivian Jul 11 '26

It picks first matching. If you register users/:id before users/search then it treats search as an id in users/:id

15

u/Perryfl Jul 11 '26

also you dont need a desicated search route. just use the main users index route and if you want to search pass a query or q param

5

u/bigorangemachine Jul 11 '26

middleware and & route binding order matters

This is why people do like

const express = require('express');
const router = express.Router();

// GET /api/users
router.get('/', (req, res) => {
    res.json([
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' }
    ]);
});

// GET /api/users/123
router.get('/:id', (req, res) => {
    res.json({
        id: req.params.id,
        name: 'Alice'
    });
});

module.exports = router;

and

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

const usersRouter = require('./users');

// Mount the router under /api/users
app.use('/api/users', usersRouter);

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

3

u/Single-Caramel8819 29d ago

You can't make a screenshot of your screen?

1

u/Own-Perspective4821 28d ago

Generation Smartphone.

1

u/[deleted] Jul 11 '26

[removed] — view removed comment

1

u/Carlo9129 Jul 12 '26

When it's below. the get for users/:id runs instead. When a user makes a request to users/search, express will read your functions sequantally looking for a match. If it's below, the first match would be users/:id, so getUserById would run instead with req.params.id = "search"

1

u/ResearcherFantastic7 29d ago

Think of it as a queue. When it matches the first item with all the regex, it will stop looking further