Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    hapi.js - Serving static files


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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 but it's not found. I'll add a route, watching for an HTTP get for the path /

    In the header function I'll use path.join to specify the path to my 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.

    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 file, refresh the browser, and the image is returned and displayed.

    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.

    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 file is now being served via the Directory handler.