hapi.js - Serving static files

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 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.

egghead
egghead
~ 35 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today