Serving Static Content

This tutorial is compatible with hapi v17

Overview

Inevitably while building any web application, the need arises to server a simple file from disk. There is a hapi plugin called inert that adds this functionality to hapi through the use of additional handlers.

First you need to install and add inert as a dependency to your project:

npm install @hapi/inert

Inert

The inert plugin provides new handler methods for serving static files and directories, as well as adding a h.file() method to the toolkit, which can respond with file based resources.

Relative paths

To simplify things, especially if you have multiple routes that respond with files, you can configure a base path in your server and only pass relative paths to h.file():

  1. 'use strict';
  2.  
  3. const Hapi = require('@hapi/hapi');
  4. const Path = require('path');
  5.  
  6. const start = async () => {
  7.  
  8. const server = Hapi.server({
  9. routes: {
  10. files: {
  11. relativeTo: Path.join(__dirname, 'public')
  12. }
  13. }
  14. });
  15.  
  16. await server.register(require('@hapi/inert'));
  17.  
  18. server.route({
  19. method: 'GET',
  20. path: '/picture.jpg',
  21. handler: function (request, h) {
  22.  
  23. return h.file('picture.jpg');
  24. }
  25. });
  26.  
  27. await server.start();
  28.  
  29. console.log('Server running at:', server.info.uri);
  30. };
  31.  
  32. start();

When you set an option under server.options.routes, such as above, it will apply to all routes. You can also set these options, including the relativeTo option on a per-route level.

h.file(path, [options])

Now, let's see how to use the h.file() method:

  1. const start = async () => {
  2.  
  3. const server = Hapi.server();
  4.  
  5. await server.register(require('@hapi/inert'));
  6.  
  7. server.route({
  8. method: 'GET',
  9. path: '/picture.jpg',
  10. handler: function (request, h) {
  11.  
  12. return h.file('/path/to/picture.jpg');
  13. }
  14. });
  15.  
  16. await server.start();
  17.  
  18. console.log('Server running at:', server.info.uri);
  19. };
  20.  
  21. start();

By requiring the inert plugin, you get access h.file() method. Here, you tell h.file() the path of the image you want to return. In this case, '/path/to/picture.jpg'.

File handler

An alternative to using the h.file() method would be to use the file handler:

  1. server.route({
  2. method: 'GET',
  3. path: '/picture.jpg',
  4. handler: {
  5. file: 'picture.jpg'
  6. }
  7. });

File handler options

You can also specify the parameter as a function that accepts the request object and returns a string representing the file's path (absolute or relative):

  1. server.route({
  2. method: 'GET',
  3. path: '/{filename}',
  4. handler: {
  5. file: function (request) {
  6. return request.params.filename;
  7. }
  8. }
  9. });

It can also be an object with a path property. When using the object form of the handler, you can do a few additional things, like setting the Content-Disposition header and allowing compressed files like so:

  1. server.route({
  2. method: 'GET',
  3. path: '/script.js',
  4. handler: {
  5. file: {
  6. path: 'script.js',
  7. filename: 'client.js', // override the filename in the Content-Disposition header
  8. mode: 'attachment', // specify the Content-Disposition is an attachment
  9. lookupCompressed: true // allow looking for script.js.gz if the request allows it
  10. }
  11. }
  12. });

Directory handler

In addition to the file handler, inert also adds a directory handler that allows you to specify one route to serve multiple files. In order to use it, you must specify a route path with a parameter. The name of the parameter does not matter, however. You can use the asterisk extension on the parameter to restrict file depth as well. The most basic usage of the directory handler looks like:

  1. server.route({
  2. method: 'GET',
  3. path: '/{param*}',
  4. handler: {
  5. directory: {
  6. path: 'directory-path-here'
  7. }
  8. }
  9. });

Directory handler options

The above route will respond to any request by looking for a matching filename in the directory-path-here directory. Note that a request to / in this configuration will reply with an HTTP 403 response. You can fix this by adding an index file. By default hapi will search in the directory for a file called index.html. You can disable serving an index file by setting the index option to false, or alternatively you can specify an array of files that inert should look for as index files:

  1. server.route({
  2. method: 'GET',
  3. path: '/{param*}',
  4. handler: {
  5. directory: {
  6. path: 'directory-path-here',
  7. index: ['index.html', 'default.html']
  8. }
  9. }
  10. });

A request to / will now first try to load /index.html, then /default.html. When there is no index file available, inert can display the contents of the directory as a listing page. You can enable that by setting the listing property to true like so:

  1. server.route({
  2. method: 'GET',
  3. path: '/{param*}',
  4. handler: {
  5. directory: {
  6. path: 'directory-path-here',
  7. listing: true
  8. }
  9. }
  10. });

Now a request to / will reply with HTML showing the contents of the directory. When using the directory handler with listing enabled, by default hidden files will not be shown in the listing. That can be changed by setting the showHidden option to true. Like the file handler, the directory handler also has a lookupCompressed option to serve precompressed files when possible. You can also set a defaultExtension that will be appended to requests if the original path is not found. This means that a request for /bacon will also try the file /bacon.html.

Static file server

One common case for serving static content is setting up a file server. The following example shows how to setup a basic file serve in hapi:

  1. const Path = require('path');
  2. const Hapi = require('@hapi/hapi');
  3. const Inert = require('@hapi/inert');
  4.  
  5. const init = async () => {
  6.  
  7. const server = new Hapi.Server({
  8. port: 3000,
  9. routes: {
  10. files: {
  11. relativeTo: Path.join(__dirname, 'public')
  12. }
  13. }
  14. });
  15.  
  16. await server.register(Inert);
  17.  
  18. server.route({
  19. method: 'GET',
  20. path: '/{param*}',
  21. handler: {
  22. directory: {
  23. path: '.',
  24. redirectToSlash: true
  25. }
  26. }
  27. });
  28.  
  29. await server.start();
  30.  
  31. console.log('Server running at:', server.info.uri);
  32. };
  33.  
  34. init();

The first thing you do is require both inert and path. As you will see, you will need both of these to get our file server up and running.

Next, you configure server.options.routes. You set the location the server will look for the static files by setting the relativeTo option.

After your server is configured, you then register the inert plugin. This will allow you to have access to the directory handler, which will enable you to server your files. In the directory handler, you configure path, which is required, to look in the entire public directory which you specified in the relativeTo option. The second option is the redirectToSlash option. By setting this to true, you tell the server to redirect requests without trailing slashes to the same path with those with the trailing slash.