hapi — How to Reply a JSON Response

Within last week’s tutorial, you’ve learned how to reply rendered HTML for a given request. Obviously, there are situations where replying HTML won’t fit your needs and you want to send JSON data as a response. This guide will show you how to reply JSON for a given request using hapi.

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

hapi Series Overview

Reply JSON as a Response

In a previously published article about routing in hapi, we already introduced the reply interface and the allowed arguments as the response payload. The reply interface accepts multiple types (e.g. string, buffer, stream, JSON serializable object) as payload. And that means, we can use any regular JavaScript object as an argument for reply() and hapi will automatically convert it into valid JSON.

Let’s make things approachable and define an exemplary route that simply responds a given request with a static JS object:

hapi v17

server.route({  
  method: 'GET',
  path: '/',
  handler: (request, h) => {
    var data = {
      key: 'value',
      another: false,
      number: 10,
      func: function() {
        return this.number * 10
      }
    }

    return data
  }
})

hapi v16

server.route({  
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    var data = {
      key: 'value',
      another: false,
      number: 10,
      func: function() {
        return this.number * 10
      }
    }

    reply(data)
  }
})

The data object is very basic. Of course, you can create more complex objects including nested ones and arrays, etc. Hapi will do the work for you and convert the given data properly. As you can see, the data object also contains a function. You’ll recognize what hapi does in those situations in a second.

If you want to check the response, just request your defined route that reply’s with JSON in your browser or use a tool like Postman for debugging purposes. The response payload for the above defined data object looks like this.

{
  "key": "value",
  "another": false,
  "number": 10
}

As you can see, hapi creates valid JSON payload that can be consumed and processed by any client. Any function within the object that should be replied will be omitted. That’s straight forward, isn’t it? Hapi ships with functionality to reply JSON data by default!

Outlook

This guide showed you how to leverage hapi and the integrated functionality to reply JSON data as the response payload. Hapi also converts the given JS object into valid JSON without further developer interference.

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!

Explore the Library

Find interesting tutorials and solutions for your problems.