hapi — Validate Query and Path Parameters, Payload and Headers All at Once on Your Routes

Validating user input is crucial to your application and you should never trust the incoming request data. Please make sure you’re validating the provided user data before sending it to your database. You never know when a user tries to DROP TABLE users.

Within the related tutorials, you can see the usage of validation on each individual type: query parameters, path parameters, request payload and request headers. And within this guide, you’re going to combine all those types on a single route!

hapi Series Overview

Prepare Your Project and Install Joi

To apply validation in hapi, you can and should use the joi module from within hapi’s plugin ecosystem. Joi allows you to define rules that get validated against the provided values. 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 ready to make use of joi for data validation.

Validate All Incoming Request Data

Validation is built into the core of hapi and you can add a validate object to your route configuration including the specifications for the individual validation assignments, like query for query parameters, params for path parameters, and so on.

The following snippet illustrates the route setup including validation for the mentioned request data types: query, params, payload, headers

const Joi = require('joi')

server.route({  
  method: 'POST',
  path: '/{page}',
  config: {
    handler: …,
    validate: {
      query: {
        test: Joi.number().optional()
      },
      params: {
        page: Joi.string().required()
      },
      payload: {
        username: Joi.string().optional()
      },
      headers: {
        'user-agent': Joi.string()
      },
      options: {
        allowUnknown: true
      }
    }
  }
})

The validate object is straight forward. Define a separate object for query, params, payload and headers and within those objects, provide the named parameters with their validation rules. Joi offers a simple to read and chainable interface with a rich API of configurations that can be applied!

Please remember that once you define validation rules for a named parameter like the user-agent in headers, it’s not possible to accept requests that contain other header fields, like host, accept-encoding, cache-control, etc. without setting validate.options.allowUnknown: true. Only requests with the single header field for user-agent pass the validation successfully without the option to allow additional and unknown properties! Please find more information in the linked joi documentation.

Outlook

This tutorial walked you through the setup of multiple types of validation to an individual route. Combine the validations freely as you’re adding routes to your hapi server.

During the last months, we’ve touched all types of validations for query and path parameters, request payload and request headers. You’re ready for the next level, which means that you should trim/sanitize/escape request parameters and payload. Don’t worry, we’ve got you covered in the upcoming tutorial!

We’re happy to hear your thoughts and comments. Please don’t hesitate to use the comments below or find us on Twitter @futurestud_io. Let us know what you think!

Enjoy coding & make it rock!

Explore the Library

Find interesting tutorials and solutions for your problems.