DEV Community

loading...

NextJS APIs validator with Middleware

meddlesome profile image meddlesome ・2 min read

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(validations.map((validation) => validation.run(req)))

    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(
    validateMiddleware([
        check('first_name').isLength({min:1, max: 40}),
        check('day').isInt({ min: 1, max: 31}),
        check('gender').isIn(['male','female']),
        check('mobile_phone').isMobilePhone(['th-TH']),
        check('boolean').isBoolean(),
    ], 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)

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

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

Discussion

pic
Editor guide