hapi.js - Serving static files

Mike Frey
InstructorMike Frey

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 4 years ago

hapi does not support serving static files out of the box. Instead it relies on a module called Inert. This lesson will cover serving static files using Inert's custom handlers.

[00:00] My Hapi server is set up to run on port 8000, and I've already registered the inert plugin. My browser is looking for a file called hapi.ping but it's not found. I'll add a route, watching for an HTTP get for the path /hapi.ping.

[00:25] In the header function I'll use path.join to specify the path to my hapi.ping file and pass the path into the reply file method added by the inert plugin. Now when the browser is refreshed, the file asserts correctly. Inert also adds a custom route handler for serving files. To use it, I'll remove the handler function and add an object literal in its place.

[00:54] The custom handler is called File, and its value should be the path to the file you want to serve through the route. I'll set it to the path to the hapi.ping file, refresh the browser, and the image is returned and displayed.

[01:05] Surfing one file per route isn't very practical. That's why inert has a custom route handler for serving entire directories. I'll replace the file handler with one called Directory. The Directory handler should be an object with a path key that points to the directory you'd like to serve.

[01:21] I'll give it a path to my public directory, then change the route path to a wildcard param that will catch any unmatched route, and look for a file to serve. Refreshing the browser shows that the hapi.ping file is now being served via the Directory handler.