Ben
Ben

Reputation: 16679

Handling route alias with query params

In Express, is there a better way to do the following?

The issue is that the redirect causes a separate request. So I'm wondering if there is a better way?

// List disabled users
router.get(
    '/disabled', (req,res,next) => {
         res.redirect(`${req.baseUrl}?isEnabled=false`);
    }
);

 // List multiple users
router.get('/',
   getMultipleUsers // This accepts query params for sorting, filtering, pagination, etc
)

Basically, /disabled is an "alias" for ?isEnabled=false.

Is there a standard way of handling this in Express?

Upvotes: 0

Views: 325

Answers (1)

James
James

Reputation: 82136

You could just manipulate the request and leverage the Express middleware process here e.g.

router.get('/disabled', (req, res, next) => {
  req.query.isEnabled = false;
  return next('/');
});

So my initial answer above was unfortunately a misunderstanding. It's explained in the docs that routes can be skipped (or exited early) via next('route') - it was my interpretation that route in this instance was whatever route URL you wanted to target e.g. next('/some-url'), that isn't the case, passing 'route' to next is actually a special use-case that's handled internally, anything else passed to next results in an error, as explained in the docs

If you pass anything to the next() function (except the string 'route'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions

It was originally my understanding that only if an Error object was passed to next this would happen, that clearly isn't the case

With this understanding, and considering ordering is important for other routes you may have e.g. /:id, the idea of letting the request "fall through" the /disabled route into / will no longer work as it would be caught be /:id beforehand. This being the case, I think your best bet here is to still manually set the query parameter as per the example, but also set the URL to match the desired route e.g.

router.get('/disabled', (req, res, next) => {
  req.query.isEnabled = false;
  req.url = '/';
  return next();
});

router.get('/:id', ...);

router.get('/', getMultipleUsers);

Upvotes: 1

Related Questions