Skip to content
Advertisement

Passing parameters to Express middleware not working

I’m trying to create an input validation middleware using Express. My goal is to be able to pass 2 parameters to the middleware that validates client input. The problem is, after following multiple resources (including Express docs), my middleware seems to not be working.

// input validator middleware
export const validateInput = (schema: joi.ObjectSchema) => {
    console.log('first console log');

    return (req: Request, res: Response, next: NextFunction) => {
        console.log('second console log');
        const { error } = schema.validate(req.body);
        if (error) {
            const errors = error.details.map((err) => err.message);
            next(new InvalidInput(errors));
        }

        next();
    };
};


// middleware call
const commentSchema = joi
    .object({
        content: joi.string().alphanum().min(3).required(),
    })
    .options({ abortEarly: false });

export const validateCommentInput = () => {
    validateInput(commentSchema);
};

After calling the middleware, I get to the “first console log”, but never to the second, and my API just hangs there until I force stop. My solution otherwise would be to just pass req and next as parameters to a function validateInput(req, next, commentSchema);, but I’m not sure that’s the proper way to do it. I also tried the async version with the same results.

Any help is greatly appreciated.

Advertisement

Answer

Your validateCommentInput function isn’t returning the inner function. The lack of curly braces in a lambda implies a return statement. However, using curly braces means you have to specify return.

So change this:

export const validateCommentInput = () => {
    validateInput(commentSchema);
};

to this:

export const validateCommentInput = () => validateInput(commentSchema);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement