hapi — How to Fix AssertionError, Cannot validate HEAD or GET requests

The hapi Node.js framework ships with a built-in validation mechanism for request input. You can seamlessly define a request’s validation rules on your route. Starting your hapi server with a misconfigured validation leads to assertion errors.

In this tutorial, you’ll walk through the steps to fix the assertion “Cannot validate HEAD or GET requests”.

hapi Series Overview

The Problem: Payload Validation Is Not Allowed

The problem you’re running into is that the HTTP specification doesn’t allow request payload validation for GET and HEAD requests.

Consequently, hapi won’t allow you to validate the payload on related routes. If you want to allow incoming requests sending data in the request payload, you must change the route’s method to something like POST or PUT.

The following route outlines the issue and what you

const Hapi = require('@hapi/hapi')  
const server = new Hapi.Server()

server.route({  
  method: 'GET',     // <- notice the GET method for this route
  path: '/movies',
  config: {
    auth: 'jwt',
    handler: async (request, h) => { … }
    },
    validate: {
      payload: {     // <- payload validation is not allowed on GET requests
        page: Joi.number().integer().min(1).default('1')
      }
    }
  }
})

In this sample route, you may accept the page input as a query parameter. If your payload validation is more complex, probably accepting object, you should think about changing the request’s method from GET to POST.

Summary

This tutorial uses technical wording and assumes that you know the difference between an HTTP GET and POST request. Hopefully, the example highlights the issue for your validation problem.

If you want to read more about HTTP, we wrote a dedicated tutorial on HTTP basics walking you through the details and wording.

Enjoy coding & make it rock!

Explore the Library

Find interesting tutorials and solutions for your problems.