d
Amit DhamuSoftware Engineer
 

Strip Trailing Slashes From Express Requests

1 minute read 00000 views

Using a small middleware, we can redirect (301) all requests with a trailing slash to one without.

app.use(function (req, res, next) {
  if (req.path.substr(-1) == '/' && req.path.length > 1) {
    let query = req.url.slice(req.path.length)
    res.redirect(301, req.path.slice(0, -1) + query)
  } else {
    next()
  }
})