Skip to content

Router Base Paths

We have our thingRouter.js, but app.js needs to know about it. We connect them using app.use(), and we give it a Base Path.

Futuristic highway output sign reading EXIT: /things. Perspective from inside a cyberpunk car.

Fig 1: Taking the Exit.

const thingRouter = require('./routes/thingRouter');
// Mount the router
// Any request starting with "/things" goes here
app.use('/things', thingRouter);

The magic here is that inside thingRouter.js, the router doesn’t know about the /things prefix. It only cares about what comes after.

Once you take the exit, you are no longer on the highway.

When we mount a router on /things, Express strips that part of the URL off before handing the request to the router.

  • Request URL: /things/42
  • Main App sees: /things -> passes control to thingRouter
  • Router sees: /42

So inside thingRouter.js, we must REMOVE the prefix we added in the previous lesson:

routes/thingRouter.js
// OLD (Wrong inside a mounted router)
// router.get('/things', ...)
// NEW (Correct)
// Matches /things/
router.get('/', (req, res) => res.send('List of Things'));
// Matches /things/:id
router.get('/:id', (req, res) => res.send('Details of Thing'));

We’ve effectively removed the repetitive /things prefix from inside the router file.


Express Router with Base Paths - Demo Repo

Express Guide: Router

⏭ Delivery

Traffic is flowing. Now let’s talk about the cargo. How do we send a response?