How do I do URL rewriting in Express JS 4 How do I do URL rewriting in Express JS 4 express express

How do I do URL rewriting in Express JS 4


If you want processing to continue after your change, you have to call next() in your middleware to keep the processing going on to other handlers.

app.use('/foo', function(req, res, next){    var old_url = req.url;    req.url = '/bar';    console.log('foo: ' + old_url + ' -> ' + req.url);    next();});

The doc for req.originalUrl says this:

This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.

Which certainly implies that you can change req.url to change the routing.


Related answer:Rewrite url path using node.js


If you use routers, the best solution is to use

req.url = '/new-url/';app.handle(req, res, next);

See more on this gist


Rewriting req.url doesn't work with app.use(...) for some reason.(Express 4.17.1)

Use app.get(...) instead:

// this doesn't workapp.use('/foo', function(req, res, next){  req.url = '/bar';  next()});// this worksapp.get('/foo', function(req, res, next){  req.url = '/bar';  next()});