Express req.baseUrl Property
What you’ll learn
- What
req.baseUrlcontains during request handling. - How mount paths work with routers and sub-apps.
- How
req.baseUrldiffers fromreq.pathandreq.originalUrl. - How to use it for logging and link generation.
Usage syntax
javascript
req.baseUrl1
Mounted router base path
javascript
var usersRouter = express.Router();
usersRouter.get('/:id', function (req, res) {
res.json({
baseUrl: req.baseUrl,
path: req.path,
originalUrl: req.originalUrl
});
});
app.use('/users', usersRouter);2
Nested routers and base URL
javascript
var apiRouter = express.Router();
var v1Router = express.Router();
v1Router.get('/status', function (req, res) {
res.send('Mounted at: ' + req.baseUrl); // /api/v1
});
apiRouter.use('/v1', v1Router);
app.use('/api', apiRouter);❓ FAQ
It is the URL path on which the current router or middleware was mounted.
req.baseUrl is the mount point, while req.path is the remaining path within the current route context.
Yes. On top-level app routes that are not mounted under a prefix, it may be an empty string.
No. It represents only the matched mount path segment.
Yes. It helps build logs, links, and diagnostics that respect router mount structure.
Did you know?
req.baseUrl shows the matched mount path for the current router, not the full request URL.
4 people found this page helpful
