node-restify icon indicating copy to clipboard operation
node-restify copied to clipboard

res.redirect unusable in async route handler.

Open robinp7720 opened this issue 2 years ago • 2 comments

  • [x] Used appropriate template for the issue type
  • [x] Searched both open and closed issues for duplicates of this issue
  • [x] Title adequately and concisely reflects the feature or the bug

Restify Version: 9.0.0-rc.3 Node.js Version: v16.13.0

Expected behaviour

Redirect shouldn't need the next callback parameter anymore.

Actual behaviour

Impossible to use res.redirect from an async route handler

Repro case

Call res.redirect from an async route handler

Cause

The direct function requires the next callback function to be passed.

Are you willing and able to fix this?

Yes, but I'm not sure how it should be fixed, or if this is even intentional.

robinp7720 avatar Jun 07 '22 10:06 robinp7720

Thanks for the heads up! Until we can get a fix in, you might be able to work around this in the meantime by doing something like:

async function helloworldRedirect(req, res) {
  return res.redirect('./helloworld', (v) => v);
}

Passing a next function like (v) => v and returning the return value of res.redirect should effectively accomplish the same thing as passing next in a non-async handler if I'm reading the code right.

josephharrington avatar Jun 17 '22 20:06 josephharrington

Another alternative: use a callback handler that wraps an async function with your actual functionality:

function redirectHandler(req, res, next) {
  redirectHandlerImpl(req)
    .then(url => res.redirect(url, next))
    .catch(next)
}

async function redirectHandlerImpl(req) {
  // do some stuff...
  return url
}

This still feels like a bit of a hack though. Restify needs an official way to invoke redirects from async handlers.

carycodes avatar Nov 13 '23 21:11 carycodes