Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    hapi.js - Replying to Requests

    Mike FreyMike Frey

    hapi's reply interface is one of it's most powerful features. It's smart enough to detect and serialize objects, buffers, promises and even streams. This video will demonstrate first hand how to use the reply method to send your data to the client, no matter the format.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Hapi's route reply method is used to end a request and signal to the framework that a response should be sent to the client. When called without arguments, Hapi responds with a 200 and empty payload.

    In general, reply looks for two arguments following the idiomatic error-first pattern of node.js callbacks. However, Hapi does not require that the error is argument is used. Reply will inspect the first arguments type, only responding with an error if the first argument is in fact an error. Otherwise, it assumes that it should be the response payload.

    Hapi will also make assumptions about how to respond to the client based on other types passed to reply. When replying with an object, Hapi changes the content type header to application JSON and stringifies the object. If a promise is passed into reply, Hapi will wait for the promise to resolve or reject, then serve the result or error.

    Reply can also handle streams. I'll create a read stream for the current file, and Hapi will handle piping it to the response stream and all the cleanup. Now the content of my index file is returned to the client. If I pass an error object to reply, Hapi will respond to the client with a 500 error.

    Responding that way from an error isn't always ideal. Internally, Hapi wraps the error in a Boom object. We can use Boom to respond with a different error type. I'll require in Boom, then pass Boom.notfound into reply. Now the request responds with 404 not found instead of a 500.