DEV Community

meddlesome
meddlesome

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
Enter fullscreen mode Exit fullscreen mode

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)
        })
      })
  }
Enter fullscreen mode Exit fullscreen mode

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() })
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (3)

Collapse
 
typicoul profile image
Luteya Coulston

This saved me, thanks

Collapse
 
hernandemonteiro profile image
Hernande Monteiro

love this solution...
thanks!

Collapse
 
davistran86 profile image
davistran86

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

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.