How to send files using Hapi

This tutorial is compatible with Hapi v17.8.1

The Inert plugin provides a wide range of functionality to work with files in routes in Hapi.

First of all you need to install the Inert module to your app using NPM or Yarn and register it before your server will start.
You can install it in terminal using the next commands:

The example of simple app:

To send a file in the Hapi there is a method “res.file()”. The first argument its the path to file, the second argument to pass an options. To send a file in Hapi as an attachment we need to pass the “mode: ‘attachment'” in options object:

Server will send this “image.png” as an attachment and user will receive it to “Downloads” folder in browser. An example of app:

To show this “image.png” in browser we can just call the “res.file” method without “options” argument:

If we want to override the filename we can use the “filename” property of “options”:

For example, to send the pre-compressed version of the file, we can use the “lookupCompressed” property of “options”:

Learning Hapi.js? Buy my Hapi.js Handbook🔥

How to make redirect in Hapi

This tutorial is compatible with Hapi v17.8.1
To create a simple redirect we can use the .redirect() method in the handler of route. This method takes a relative or an absolute URI used to redirect the client to the passed resource. It sets the 302 HTTP redirection:

Also, the second way to set the 302 redirect:

The 301 or permanent redirect you can make in two ways:

OR using the .permanent method:

The full example of server:

Learning Hapi.js? Buy my Hapi.js Handbook🔥