hapi — Request Payload Validation With Joi

Within last week’s tutorial you’ve learned how to access the request payload in hapi. Because you should never, ever trust provided data submitted by users, a common process is to validate the request payload against a given rule set. hapi streamlines this procedure and integrates a validation process for object schemas with the help of joi.

This guide shows you how to use joi and configure payload validation for incoming requests on a given route.

Before diving into the details, have a look at the series outline and find posts that match your interests and needs.

hapi Series Overview

Prepare Your Project and Install Joi

You’ll use the joi module from within hapi’s plugin ecosystem to validate selected fields within the request payload. Before defining the validation itself, you need to add joi as a dependency to your project:

npm i -S joi  

Installation process finished successfully? Your project is prepared to make use of joi for input validation.

Use Joi for Payload Validation

Incoming requests pass a pre-defined list of actions like route lookup that matches the request’s path, parse cookies, authenticate the request, parse payload and many more. Once the request payload is parsed and available, the validation procedure gets kicked off. If you didn’t define any validation, hapi skips this step and proceeds with the route handler.

In case you’ve payload validation in place, hapi applies the defined constraints. Depending on whether the given payload data passes the validation process successfully, the request will be proceeded by calling the route handler. If validation fails, hapi will reply with a detailed boom error object including the reason why validation failed.

Let’s get practical and have a look at code that illustrates the application of payload validation for a given hapi route. The route’s handler is located aside the validate configuration within the config object of your route:

var Joi = require('joi')

server.route({  
  method: 'POST',
  path: '/',
  config: {
    handler: …,
    validate: {
      payload: {
        email: Joi.string().email().required(),
        password: Joi.string().min(6).max(200).required()
      }
    }
  }
})

As you can see, the validate object requires you to further specify the validation type, like payload, query parameter and params which describes the path parameters. Within your individual payload object, define the properties that will be checked for incoming requests.

In the example above, you can see that the email and password fields within the request payload will be validated against the given joi rules. email needs to be a valid email string and is a required field. password is a string with a minimum length of 6, maximum length of 200 characters and also a required property. Of course, you can define your validation rules of choice. Within Joi’s API documentation, you’ll find all applicable methods.

In case the validation doesn’t pass successfully, you’ll receive the aforementioned boom error object. The following code block shows the detailed raw response payload that will be sent to the requester.

Raw Response Payload

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "child \"password\" fails because [\"password\" length must be at least 6 characters long]",
  "validation": {
    "source": "payload",
    "keys": [
      "password"
    ]
  }
}

Actually, you’ll receive a proper 400 Bad Request HTTP response and the content from the code snippet above is contained within the response body.

The message property indicates the error details and what to adjust within future requests to avoid the issue. Within the validation field, you can find the keys that caused the error. Also, the error object contains the statusCode and HTTP error as individual fields.

Outlook

We hope you enjoyed this guide on payload validation and take away the insights on how to improve your code by validating fields as early as possible. Validating incoming user data as early will keep your code base clean and small. You don’t need to perform the validation steps yourself within the route handler.

Benefit from hapi’s functionality and put in some brainpower to get going with joi and what rules are applicable for the request payload, query and path parameters.

The request payload isn’t the only option to pass data from clients to server. Validate query parameters as well.

We appreciate feedback and love to help you if there’s a question on your mind. Let us know in the comments or on twitter @futurestud_io.

Make it rock & enjoy coding!


Additional Resources

Explore the Library

Find interesting tutorials and solutions for your problems.