Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Chaining middleware in next-connect fails with error handler

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"

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda