Prudent Devs

In-depth guide to handling routes in hapijs

Routes help us to add functionality to our web-apps. Understanding how to add routes to hapijs apps.

#code , #nodejs , #hapijs , #tsc

This post is part of Learn to build web-applications with Hapi and Typescript

The web works based on URLs. Take stackoverflow for example. takes us to the homepage, takes us to the questions page, takes us to the users page, and so on.

In hapi, server.route determines how a web-app should handle urls typed by a user. In this post, let us understand the elements of server.route.

Let us start with the basic hello world program we wrote in the first post.

"use strict";

import * as hapi from "hapi";

const server: hapi.Server = new hapi.Server()
server.connection({ port: 3000 });

	method: "GET",
	path: "/",
	handler: (request: hapi.Request, reply: hapi.IReply) => {
		reply("Hello World")


server.start((err) => {
	if (err) {
		throw err;
	console.log("server running at 3000");

Here, server.route defines a route to handle the / url. There are three elements we see in this route: method, path, and handler. Let us understand these three elements in detail.

Route Methods

Every http request contains a method. It will be one of GET, POST, PUT, or DELETE. There are other methods too, but for our discussion, we will limit to these methods. Below table explains these methods with an example.

| method | Usage | Example | |