Rewriting req.url in router with prefix path results in missing slash (/)
Author: fchuCreated Sep 19, 2019Updated Aug 11, 2026
Labels4.xinvestigatemodule:router
Hello, I've been trying to use a npm module (connect-history-api-fallback) and encounter problems that after a lot of debugging I believe boils down to this issue.
When you're in a router that has a mount path, doing a rewrite on the relative root ('') path result in a missing slash, eg with bug.js as below
const express = require('express')
const app = express()
const port = 3000
var router = express.Router();
router.get('/', function (req, res, next) {
req.url = "/index.html"
next()
});
app.use('/app', router);
app.use(function (req, res, next) {
console.log("Rewritten path: " + req.url)
res.end()
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Running the following commands:
node bug.js
curl localhost:3000/app
results in the rewritten path to be /appindex.html instead of /app/index.html
Environment:
"node": 12.10.0
"express": 4.17.1
This sounds like a bug to me, but maybe I'm doing something wrong? I'm not too expert in expressjs to know for sure (my hunch is the router code doesn't 'remount' the prefix path properly.
Thanks!
Source: expressjs/express