In some cases users wants to alter existing HTTP API responses, by removing excess fields, changing content or modify result in any other way.

In this chapter we will go trough process step by step and describe how to remove explorer property from the /node/configuration route accessible on GET method.

2 "data": {
3 "symbol": "TѦ",
4 "explorer": "",
5 "version": 23,
6 }

Desired response:

2 "data": {
3 "symbol": "TѦ",
4 "version": 23,
5 }


Get route

First we need get existing route object that we want to modify. Be aware there can be two Server instances accessible via Identifiers.HTTP or Identifiers.HTTPS symbols. Each Server instance expose getRoute method which is used for obtaining ServerRoute.

1const route =<Server>(Identifiers.HTTP).getRoute("GET", "/api/node/configuration");

Keep original handler

Save the reference to existing handler. Use bind() function to bind original object which method belongs to, otherwise you will lose this reference if one is used inside the handler.

1const originalHandler = route.settings.handler.bind(route.settings.bind);

Create new handler

Replace route handler with new wrapper function. New function will call original handler and set desired property to undefined. JSON standard defined that undefined properties are not included in stringified response, which will result as removed field in response body. Finally return modified response.

1route.settings.handler = async (request: Hapi.Request, h: Hapi.ResponseToolkit) => {
2 const response = await originalHandler(arguments);
3 = undefined;
4 return response;
5 };



Server.getRoute(method: string, path: string) : ServerRoute | undefined


method - HTTP method eg. “GET”, “POST” path - route path eg. “/api/node/configuration”


Returns ServerRoute object or undefined.

Complete code sample

1// Import
2import Hapi from "@hapi/hapi";
4// Modify route
5const route =<Server>(Identifiers.HTTP).getRoute("GET", "/api/node/configuration");
6if (route) {
7 const originalHandler = route.settings.handler.bind(route.settings.bind);
8 route.settings.handler = async (request: Hapi.Request, h: Hapi.ResponseToolkit) => {
9 const response = await originalHandler(arguments);
10 = undefined;
11 return response;
12 };

Additional reading

Last updated 2 years ago
Edit Page