DEV Community


Posted on

NextJS APIs validator with Middleware

Validate the request.body is a must for every APIs development. NextJS is able to use Connect compatible Middlewares for an extendable feature on top of each request/response like ExpressJS.

Here is a guide to integrating the express-validator, a wrapper of validator.js inside your NextJS application.

First, Install express-validator in NextJS project

yarn add express-validator

Next, Create NextJS Middleware Helper Method as /lib/init-middleware.js

export default function initMiddleware(middleware) {
    return (req, res) =>
      new Promise((resolve, reject) => {
        middleware(req, res, (result) => {
          if (result instanceof Error) {
            return reject(result)
          return resolve(result)

Next, Create NextJS Validator Middleware to handle error and response out as /lib/validate-middleware.js

export default function validateMiddleware(validations, validationResult) {
  return async (req, res, next) => {
    await Promise.all( =>

    const errors = validationResult(req)
    if (errors.isEmpty()) {
      return next()

    res.status(422).json({ errors: errors.array() })

Now it's time to integrate validate rules and middleware into your NextJS API Routes. You can use any validator.js's validator functions as sample below.

import initMiddleware from '../../../lib/init-middleware'
import validateMiddleware from '../../../lib/validate-middleware'
import { check, validationResult } from 'express-validator'

const validateBody = initMiddleware(
        check('first_name').isLength({min:1, max: 40}),
        check('day').isInt({ min: 1, max: 31}),
    ], validationResult)

export default async (req, res) => {
  switch (req.method) {
    case "POST":
      await validateBody(req, res)

      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })

      nextFunction(req, res)

      res.status(404).json({ message: "Request HTTP Method Incorrect." })

Now the express-validator will be working on top of each HTTP Request to validate your request.body in NextJS API Route :)

Discussion (2)

typicoul profile image
Luteya Coulston

This saved me, thanks

davistran86 profile image

Thanks a lot, this is exactly what I'm looking for