hapi — How to Access and Handle Request Payload

Up to this point, you’ve mastered 14 tutorials on hapi in this beginner series. Finally, we’re arriving at the point where you’re gonna handle and make use of large data sets arriving at your server. Actually, it doesn’t need to be a large data set that comes in and waits for handling. It’s just to illustrate what this guide is about: access and handle the incoming request payload.

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

hapi Series Overview

Access Request Payload

With any request that touches your server, you’re receiving (a ton of) information from the client. Details like HTTP method, request URL, headers, query and path parameters, and of course the request payload if available (and allowed). You can access all the information by using hapi’s request object that is provided for each handler(request, reply) function.

In previous tutorials, you’ve learned how to access query parameter and also how to manage optional and wildcard path parameters. Now you’re also interested in another kind of data that comes from clients: the request payload.

The following code snippet illustrates how to access the request payload in a hapi route handler:

hapi v17

server.route({  
  method: 'GET',
  path: '/',
  handler: (request, h) => {
    var payload = request.payload   // <-- this is the important line

    return payload
  }
})

hapi v16

server.route({  
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    var payload = request.payload   // <-- this is the important line

    console.log(payload)

    reply(payload)
  }
})

As you can see, it’s a straight forward process and the payload is accessible via request.payload. The incoming payload gets parsed and provided to you as a JavaScript object.

Notice: the payload may contain unsafe data, so make sure you’re going to escape string sequences or apply validation rules! You’ll learn about payload validation within the upcoming tutorial.

Outlook

Even though this tutorial is straight to the point, it includes and outlines the necessary details to access the request payload in your route handler. Be cautious with the incoming information and never, ever trust any user data!

Besides request payload, you should know how to handle query parameters in hapi 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.