Chaining middleware in next-connect fails with error handler

839 views Asked by At

I have following two middleware functions:

function validateEmail(req, res, next) {
  console.log('email validation');
  if (req.body.email && req.body.email.match(EMAIL_REGEX)) {
    console.log('email OK!');
    return next(req, res);
  } else {
    console.log('email wrong');

    res.json({ message: 'email invalid'});
  }
}
function  validateOriginHeader(req, res, next) {
  if (ORIGIN_WHITELIST.includes(req.headers.origin)) {
    console.log('header OK!');
    return next(req, res);
  } else {
    console.log('header wrong!');
    res.status(403);
    res.end('game over');
  }
}

I try to use them in next-connect setup in pages/api, where i define onError and onNoMatch options:

// factory fn returns new instance of newConnect with default setup
function factory() {
  return nextConnect({
    onError(err, req, res) {
      console.log('error?:', Object.keys(err));
      res.status(500).json({ message: 'Internal Server Error' });
    },
    onNoMatch(req, res) {
      res.status(405).json({ message: `Method ${req.method} is not allowed.` });
    },
  });
}
// pages/api/subscribe.js 
export default factory()
  .use(validateOriginHeader)
  .use(validateEmail)
  .post(async (req, res) => {
    try {
      const mailchimpRes = await mailchimp.subscribe(req.body);
      res.json(mailchimpRes);
    } catch (e) {
      res.json(e);
    }
  });

The problem:

Only first middleware executes (printing 'header OK!' on server console). Console in validateEmail never prints. When I console err in onError handler defined in next-connect options, it looks like request object, ie. it contains body with the email payload.

Calling the route results in 500: Internal Server Error is returned (as defined in onError handler).

What is wrong with this setup?

versions used:

"next": "11.1.2" "next-connect": "0.10.2"

1

There are 1 answers

0
ABDULLOKH MUKHAMMADJONOV On BEST ANSWER

You have to call next() with empty arguments instead of next(req, res). Calling next() with a parameter(s) results in onError