Detect the matched router prefix
A router serves multiple mounted prefixes and needs to identify which prefix matched the current request.
Express.js · Pipe
req.baseUrl is the URL path where the current Express router was mounted. It reports the concrete path matched for the request, not the pattern used to mount the router.
req.baseUrl is a request property containing the path where the current router was mounted. It reports the concrete matched path, even when the router was mounted using a pattern or several patterns; req.originalUrl combines this value with req.url.
req.baseUrl| Name | Type | Description |
|---|---|---|
req | Express request object | The Express request object whose mounted-router path is being read. |
String: the URL path on which a router instance was mounted.
app.mountpath, but it is read from the request and describes the router involved in that request.app.mountpath exposes matched path pattern definitions./greet, the router prefix is exposed as /greet./hello.req.originalUrl, which combines the base and router URL.const express = require('express');
const app = express();
const router = express.Router();
router.get('/jp', (req, res) => {
res.json({ baseUrl: req.baseUrl, originalUrl: req.originalUrl });
});
app.use('/greet', router);
app.listen(3000);Run the app and request /greet/jp to see /greet as the mounted router path and /greet/jp as the original URL.
A router serves multiple mounted prefixes and needs to identify which prefix matched the current request.
Middleware needs to distinguish a router's mounted path from the remaining request URL.
Diagnostics need to compare the mounted prefix with the full original request URL.
req.baseUrl represent?It is the URL path on which the current router instance was mounted. For a request to /greet/jp handled by a router mounted at /greet, its value is /greet.
Follow-up: How does it differ from app.mountpath? req.baseUrl contains the matched string for the request, whereas app.mountpath returns the matched path pattern or patterns.
A router mounted with a pattern can match different concrete paths. req.baseUrl reports the concrete matched string rather than the pattern definition.
Follow-up: How can the complete original request URL be reconstructed? The documentation describes req.originalUrl as a combination of req.baseUrl and req.url.
req.baseUrl relate to req.originalUrl?req.baseUrl identifies the router's mounted prefix. req.originalUrl is the related complete URL value formed from req.baseUrl and req.url.
Follow-up: Which property can be rewritten for internal routing purposes? req.url can be freely rewritten, while req.originalUrl retains the original request URL.
req.originalUrlreq.urlapp.mountpathreq.route