hapi.js - Replying to Requests

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet

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.

[00:01] 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.

[00:12] 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.

[00:33] 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.

[01:01] 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.

[01:26] 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.