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

161
Vistas
best practice to validate POST request body

My Express API exposes a POST endpoint to create a user, and i need to validate data before inserting it into database, i have two methods in mind:

Method 1: Include the model's validation in the controller and repeat it for every model:

// controllers/users.js

exports.createUser = async function (req, res) {
    const { username, email, password } = req.body;

    /* validation logic */

    /* interact with db */

Method 2: Move the validation logic to dedicated middleware:

// middleware/validators.js

exports.validateArticle = function (req, res, next) {};

exports.validateComment = function (req, res, next) {};

exports.validateUser = function (req, res, next) {
    const { username, email, password } = req.body;

    /* validation logic */

    if (!isValid) {
        return res.statusCode(400);
    }

    next();
};
// routes/users.js

const { validateUser } = require('../middlewares/validators');

router.route('/').post(validateUser, createUser);

my concern with method 2 is that the logic for one endpoint method would be scattered among many files, but which one of these methods follow best practices ?

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

0

I can suggest you to use a ready-made middlewares express-validator, and setup like that:

// src/validation/validation.js
const { validationResult } = require('express-validator');

const validate = (schemas) => {
    return async (req, res, next) => {
        await Promise.all(schemas.map((schema) => schema.run(req)));

        const result = validationResult(req);
        if (result.isEmpty()) {
            return next();
        }

        const errors = result.array();
        return res.send({
            message: 'Validation error',
            errors: errors,
        })
    };
}

module.exports = {
    validate
}

this is a function that you can call like middleware in your router, then a file with validation rules.

// src/validation/validationSchemas.js
const { body } = require('express-validator');

const addUserSchema = [
    body('username').isLength({ min: 4, max: 16 }).withMessage('Username must be at least 4 and no more than 16 characters'),
    body('email').isEmail().withMessage('Incorrect email')
];

module.exports = { addUserSchema }

and in your router:

const { validate } = require('../validation/validation'); 
const { registrationSchema, loginSchema } = require('../validation/validationSchemas');

router.post('/registration', validate(registrationSchema), userController.registration);
about 4 years ago · Juan Pablo Isaza Denunciar

0

The issue is one of scale. If there are a lot of different routes in a controller, or if you just have multiple controllers, it can be difficult to keep things clean and easy to understand. The controller shouldn't have much more than what is necessary to show how incoming requests are being routed and returned. Everything else that isn't trivial should be passed to a middleware service. Therefore, the second option tends to work out better if you want room to grow.

Additionally, by putting all your validation logic together you can easily reuse code where applicable.

Option 1 can work out if this is very static and you have no expectations that new routes or controllers will be added.

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