hapi — Get Your Server Up and Running

This post kicks off a new series on hapi, a Node.js web services framework. Hapi provides a solid foundation that lets you fully focus on building your application by shipping with built-in support for plugins, authentication, caching, input validation, and many more essential features!

Honestly, we’ve build the entire Future Studio homepage using hapi and couldn’t be happier about the commitment to the hapi framework.

Throughout this series, you’ll learn about various functionalities provided by hapi or additional plugins. Actually, hapi’s plugin system is very powerful and you’ll recognize that there are many great plugins already available within the ecosystem.

You don’t need to invent the wheel as you go, just keep an eye on existing plugins that may provide your desired functionality. Anyway, we’ll get back to detailed hapi functionality later in this series.

The latest hapi version at the time of writing this tutorial is 16.6.2. That’s the version this series will be based on and we’re going to update to newer versions when possible.

As already mentioned, this is a comprehensive tutorial series on hapi and the list below outlines available guides.

hapi Series Overview

Hapi Overview

Originally, hapi was developed at Walmart by a team around Eran Hammer with the idea that configuration is better than putting everything into code. Eran still leads the open source development of hapi itself and multiple plugins within the ecosystem. Up to this day, a great collection of plugins has emerged and they all add different functionality to the framework. The modularity of hapi allows to focus on core functionality and separating features like view rendering into an extra plugin.

However, let’s stop the hapi basics for now and get our hands dirty by creating a new hapi server that serves the “hello world” message.

Examples Are Available on GitHub

We’ll provide code examples for selected posts of this series on GitHub within the fs-opensource/nodejs-tutorials-hapi repository. Of course, you’ll find code snippets for individual functions within the related blog posts as well!

Your First “Hello World” Server

In the following, you’ll create a shiny new hapi server. Create a new project folder myhapiproject on your machine that will contain the required files.

Preparations

Within this series, we’ll use NPM as a package manager to add dependencies with ease. To initialize a fresh NPM project, use npm init and provide the asked information. You can just stay with the default values and edit the information later within the created package.json file.

npm init  

Having the package.json file available, you can add hapi as a project dependency by installing the package and also save it as a dependency for your project (save hapi as a dependency by adding -S to npm install)

npm install -S hapi  

That’s all you need. You’re ready to create and spin up your first hapi server.

Your First Hapi Server

A very basic server implementation is shown in the code snippet below. First, you need to require the hapi module and initialize a new Hapi.Server(). Afterwards, add connection details by providing host and port information. Besides host and post, you can also define a Unix socket file or Windows named pipe.

Actually, that’s everything you need to spin up a very basic hapi server. Put the code below into a server.js file.

server.js

var Hapi = require('hapi')

// create a server with a host and port
var server = new Hapi.Server({  
  host: 'localhost',
  port: 3000
})

async function start () {  
  // start your server
  try {
    await server.start()
  } catch (err) {
    console.error(err)
    process.exit(1)
  }

  console.log('Server running at: ', server.info.uri)
}

start()  

The downside, you have only the command line output as visual evidence that everything went smoothly when starting the server.js file. There aren’t any routes that can be called from the browser. And that’s exactly what we’ll add in the section below!

Routes

The simple server above just doesn’t serve any information and we should add a route that responds to a request. Add a route that just serves a friendly Hello Future Studio! message when requesting your server via the browser, cURL, etc.

// add “hello world” route
server.route({  
  method: 'GET',
  path: '/',
  handler: (request, h) => {
    return 'Hello Future Studio!'
  }
})

Use the server instance and add any desired route using the route() method. The method property can be any valid HTTP method and path defines the endpoint URL for this route. Define your desired functionality within the handler function, where you’ve access to the request and response (called reply) objects.

Routes support query and path parameters as well. We’ll go in detail on route parameters in a later tutorial. For now, let’s just focus on how to define a route in general.

The complete server code should look like this:

server.js

var Hapi = require('hapi')

// create new server instance
var server = new Hapi.Server({  
  host: 'localhost',
  port: 3000
})


// add “hello world” route
server.route({  
  method: 'GET',
  path: '/',
  handler: (request, h) => {
    return 'Hello Future Studio!'
  }
})

async function start () {  
  // start your server
  try {
    await server.start()
  } catch (err) {
    console.error(err)
    process.exit(1)
  }

  console.log('Server running at: ', server.info.uri)
}

start()  

Start the updated server.js file using node server.js and open your browser. Navigate to localhost:3000 to see the Hello Future Studio! message.

You’ve made it, your first hapi server is up and running serving your hello world message. Awesome!

Outlook

This tutorial helps you to get going on hapi and provided basic information about the framework. You’ve created a hapi server from scratch and added a route to serve a hello world message.

That’s a great start to proceed on. Within the upcoming post, you’ll learn how to add routes and handle incoming traffic in hapi.

Enjoy coding & make it rock!


Additional Resources

Explore the Library

Find interesting tutorials and solutions for your problems.