Mike Mulligan
Mike Mulligan

Reputation: 198

Express - Give a base path to res.redirect()

I'm not sure if this issue is something that can easily be fixed but here's the scenario. Say we have an express app() with a separate router().

const express = require('express')
const app = express()

const router = express.Router()

router.get('/', (req, res) => {
  res.redirect('/bar')
})

app.use('/foo', router)

app.listen('8000')

Say we send a request to http://localhost:8000/foo/. I need the res.redirect('/bar') to redirect to http://localhost:8000/foo/bar instead of redirecting to http://localhost:8000/bar. The only key component here is that we cannot use redirects that are relative to the current route, so res.redirect('bar') would not be suitable for us.

Is there any way that we can override res.redirect()'s functionality to prepend /foo to every redirect? Also, I cannot modify every res.redirect() with req.originalUrl or anything similar.

Thanks a lot

Upvotes: 1

Views: 1212

Answers (1)

Mike Mulligan
Mike Mulligan

Reputation: 198

Figured out how to do it with middleware -

app.use((req, res, next) => {
  const redirector = res.redirect
  res.redirect = function (url) {
    url = '/foo' + url
    redirector.call(this, url)
  }
  next()
})

Upvotes: 1

Related Questions