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.

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

The web works based on URLs. Take stackoverflow for example. stackoverflow.com takes us to the homepage, stackoverflow.com/questions takes us to the questions page, stackoverflow.com/users 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 });

server.route({
	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 | |

Published On:
Under: #code , #nodejs , #hapijs , #tsc
Sign up for my newsletter