Request logging
A mounted middleware needs to log or audit the complete incoming path, including the mount point.
Express.js · Pipe
req.originalUrl is the original request URL, retained while Express may rewrite req.url for internal routing. It is available in middleware and routers and is represented as a string.
req.originalUrl preserves the request URL as it arrived, including its mount path, while middleware may rewrite req.url during routing. It is available in middleware and routers and corresponds to the combination of req.baseUrl and req.url.
req.originalUrlString
req.url for internal routing while continuing to inspect the preserved original URL.req.url when you need the URL before a mounted middleware or router changes it; mounting can remove the mount path from that property.const express = require('express');
const app = express();
app.use('/api', (req, res, next) => {
console.log(req.originalUrl);
console.log(req.url);
next();
});
app.get('/api/search', (req, res) => {
res.json({ originalUrl: req.originalUrl, url: req.url });
});
app.listen(3000);Run the app and request /api/search?q=express to compare the preserved original URL with the URL used inside the mounted middleware.
A mounted middleware needs to log or audit the complete incoming path, including the mount point.
Application logic rewrites req.url during internal routing but still needs the client-facing request path.
A router or middleware needs to distinguish the full request URL from the URL relative to its mount point.
req.originalUrl used for?It is a string containing the original request URL. Unlike req.url, it keeps the URL before internal routing rewrites it, including a mount path.
Follow-up: How can the original value relate to other request properties? It is the combination of req.baseUrl and req.url at the point where the request is being handled.
req.url?Mounted middleware can rewrite req.url by stripping the mount point. req.originalUrl remains available so code can inspect the incoming URL instead of the rewritten routing URL.
Follow-up: If middleware is mounted at /api and receives /api/search?q=x, what should be logged? The original URL is /api/search?q=x, while the middleware's rewritten req.url may be /search?q=x.
The documentation identifies the type as String and says the property is available in middleware and router objects. It is an Express request property used during the current request-response cycle.
Follow-up: What related value helps reconstruct it? req.baseUrl supplies the matched mount path, and req.url supplies the current routing URL.
req.urlreq.baseUrl