Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Getting Started with hapi.js
Getting Started with hapi.js

Getting Started with hapi.js: Build well-structured, testable applications and APIs using hapi.js

Arrow left icon
Profile Icon Brett
Arrow right icon
Mex$378.99 Mex$541.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
eBook Apr 2016 156 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
Arrow left icon
Profile Icon Brett
Arrow right icon
Mex$378.99 Mex$541.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (6 Ratings)
eBook Apr 2016 156 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Getting Started with hapi.js

Chapter 2. Adding Functionality by Routing Requests

In the last chapter, we saw what a sample route looks like in both vanilla Node and hapi, and how hapi is more configuration-oriented in its routing definition. In this chapter, I will expand on how hapi handles routing, making it easy to add routes in a scalable manner while being able to avoid making unnecessary mistakes. If you haven't got much experience with building web servers, this chapter will also be a good foundation in routing, covering the following topics:

  • Adding and configuring routes in hapi
  • The hapi routing algorithm
  • The hapi request life cycle
  • The hapi request object
  • The reply interface
  • Serving static files
  • Using templating engines to serve view

By the end of this chapter, you will have the tools that you need to be able to create a JSON API, a static file server, and a fully functional website using a templating library. You will also be shown some patterns to simplify less trivial requests, so the control flow...

Server routing

There are many ways to interpret a route in terms of web servers, but the easiest (or what I like to think of them as) one is the path that interacts with a particular resource on a web server. In most frameworks, including hapi, a route comprises three core properties:

  • the path through which you can access the route
  • a method by which you can access the path
  • a handler, which is a function to take an action based on the request and return the output to the user

In hapi, the handler looks like the following:

…
server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    return reply('Hello!');
  }
});
…

The preceding code should look familiar to the code sample of our server from the previous chapter. Again, like everything in hapi, we add a route by providing a configuration object with the required route properties. If any required properties are missing, the server will show an error on startup with a detailed...

hapi routing algorithm

After learning about hapi's server.route() API and configuration object, you may have found yourself curious as to how is it possible to add all these routes, in a manner that allows to you to keep your codebase manageable. You may have the following questions in mind:

  • Is it possible to have a route conflict?
  • How are routes prioritized and mapped to a request?
  • Is the order in which we register a route relevant?

Don't worry if you didn't have these questions, you'll have them soon enough. But let's answer them now.

hapi is one of the few frameworks in Node that have deterministic routing. Each request can only map to one route, and its routing table will be the same every time you start the server. This was one of the things that appealed to me initially, when I started working with Node and was researching Node frameworks in depth. As the application size and teams grow, routing conflicts become more of a concern, and I wanted to future-proof my...

hapi request life cycle

After adding a few simple routes to your server, you will eventually come to the point where you need to add things like authentication, authorization, and have other use cases that need to be solved before your handler is ever reached. There are multiple approaches to this, such as creating a function to check authentication credentials, another for assigning authorization tokens that are called when every request is received initially by the handler. You could do this in the route prerequisites mentioned previously. However, if you forget to add these to a single route, or had something executed before your authentication function is called, you've left yourself open to secure data being accessible to unauthenticated users.

The approach which hapi uses to solve this is to have a well-defined request life cycle, with a reliable series of events that happen on every request. This gives you a fairly granular control over a request in an easy-to-extend and readable...

hapi request object

In hapi, the goal is never to monkey-patch or modify any of the normal Node objects or methods, but only to provide an extra layer around them to access the important parts.

Note

Monkey patching is the method of overriding or extending the behavior of a method. For example, let's create an add function that returns the sum of two numbers:

let add = function (a, b) {
  return a + b;
}

We now want to log in to the console every time this is called, without altering the existing behavior. We would modify it by doing the following:

let oldAdd = add;
add = function (a, b) {
  console.log('add was called…');
  return oldAdd(a, b);
}

Now every time add is called, it will print add was called…, and return the sum just as before. This can be useful in modifying core language methods, but is not a recommended pattern, as it can cause very hard-to-debug side effects. I generally limit doing this to writing tests or debugging code.

This is the case with the...

The reply interface

In the various life cycle events in hapi, such as authentication, route handlers, route prerequisites, you will see reply as one of the function arguments. This is the reply interface.

Throughout this book and the API documentation, you will see the function reply in two forms—either as reply() or as reply.continue()—which have two different purposes. reply.continue() is generally used to return the control flow back to the framework and continue through the request life cycle, whereas reply() is generally used to generate the response to be returned to the client. The only exception to this is inside the route prerequisites where reply() is used, as it assigns a variable to the request.pre object.

reply() can accept two parameters (error and response), but this is rarely used, as reply always acts on the first defined parameter that it is passed in. For example, if reply() is passed two variables and the first one is not null, it treats this as an error...

Serving static files with inert

inert (https://github.com/hapijs/inert) is the static file and directory handler module for hapi. It provides a lot of useful utilities for simplifying serving static content. Let's look at one of those now:

const Path = require('path');
const Hapi = require('hapi');
const Inert = require('inert');                    // [1]
const server = new Hapi.Server();
server.connection({ port: 3000 });
server.register(Inert, (err) => {                  // [2]
  server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {                                     // [3]
      directory: {                                 // [3]
        path: Path.join(__dirname, 'public'),      // [3]
        listing: true                              // [3]
      }                                            // [3]
    }                                              // [3]
  });
  server.start((err) => {
    console...

Server routing


There are many ways to interpret a route in terms of web servers, but the easiest (or what I like to think of them as) one is the path that interacts with a particular resource on a web server. In most frameworks, including hapi, a route comprises three core properties:

  • the path through which you can access the route

  • a method by which you can access the path

  • a handler, which is a function to take an action based on the request and return the output to the user

In hapi, the handler looks like the following:

…
server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    return reply('Hello!');
  }
});
…

The preceding code should look familiar to the code sample of our server from the previous chapter. Again, like everything in hapi, we add a route by providing a configuration object with the required route properties. If any required properties are missing, the server will show an error on startup with a detailed error message, thus making it very easy to...

hapi routing algorithm


After learning about hapi's server.route() API and configuration object, you may have found yourself curious as to how is it possible to add all these routes, in a manner that allows to you to keep your codebase manageable. You may have the following questions in mind:

  • Is it possible to have a route conflict?

  • How are routes prioritized and mapped to a request?

  • Is the order in which we register a route relevant?

Don't worry if you didn't have these questions, you'll have them soon enough. But let's answer them now.

hapi is one of the few frameworks in Node that have deterministic routing. Each request can only map to one route, and its routing table will be the same every time you start the server. This was one of the things that appealed to me initially, when I started working with Node and was researching Node frameworks in depth. As the application size and teams grow, routing conflicts become more of a concern, and I wanted to future-proof my work by starting with a...

Left arrow icon Right arrow icon

Key benefits

  • With the help of this book, you will improve your productivity as a developer and that of your team by focusing on business logic utilizing the structure that Hapi.js provides
  • You will be introduced to a real-world problem and we’ll demonstrate how to use the tools Hapi provides to resolve it
  • This is the only book with a learn-by-example approach

Description

This book will introduce hapi.js and walk you through the creation of your first working application using the out-of-the-box features hapi.js provides. Packed with real-world problems and examples, this book introduces some of the basic concepts of hapi.js and Node.js and takes you through the typical journey you'll face when developing an application. Starting with easier concepts such as routing requests, building APIs serving JSON, using templates to build websites and applications, and connecting databases, we then move on to more complex problems such as authentication, model validation, caching, and techniques for structuring your codebase to scale gracefully. You will also develop skills to ensure your application's reliability through testing, code coverage, and logging. By the end of this book, you'll be equipped with all the skills you need to build your first fully featured application. This book will be invaluable if you are investigating Node.js frameworks or planning on using hapi.js in your next project.

Who is this book for?

If you are a JavaScript developer with or without Node.js experience and would like to learn to build applications, APIs, and web servers with the best-in-class framework hapi.js, this book is perfect for you.

What you will learn

  • ? Increase your productivity by taking advantage of the out-of-the-box features hapi.js provides
  • ? Build secure API servers
  • ? Create websites and applications using your favorite templating language
  • ? Leverage hapi.js plugins to better structure your codebase
  • ? Simplify your security workflows with the built-in authentication and authorization
  • functionality of hapi.js
  • ? Ensure application reliability with testing and code coverage
  • ? Reduce code complexity using reusable validation logic with joi
  • ? Gather insight into your application performance via logging
  • ? Start the journey to building robust production-ready applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 12, 2016
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781785889684
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 12, 2016
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781785889684
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,256.97
RESTful  Web API Design with Node.js
Mex$676.99
Building Slack Bots
Mex$902.99
Getting Started with hapi.js
Mex$676.99
Total Mex$ 2,256.97 Stars icon

Table of Contents

8 Chapters
1. Introducing hapi.js Chevron down icon Chevron up icon
2. Adding Functionality by Routing Requests Chevron down icon Chevron up icon
3. Structuring Your Codebase with Plugins Chevron down icon Chevron up icon
4. Adding Tests and the Importance of 100% Code Coverage Chevron down icon Chevron up icon
5. Securing Applications with Authentication and Authorization Chevron down icon Chevron up icon
6. The joi of Reusable Validation Chevron down icon Chevron up icon
7. Making Your Application Production Ready Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(6 Ratings)
5 star 33.3%
4 star 16.7%
3 star 0%
2 star 33.3%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




Eoin Shanaghy Jun 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought the paper and kindle versions of "Getting started with hapi.js" about six weeks ago. I had worked with various Node.js projects for a few years before this. Most of them used Express and I had only briefly looked at hapi. Hearing about the high quality standards of the hapi project and the clear, opinionated approach let me to look deeper so I started with this book.The best thing about this book is the clear, concise style and well thought out structure. It doesn't seem to have any agenda other than clearly explaining the subject matter and doesn't it go overboard with long-winded text. It's both accessible to a newcomer and useful for anyone with more experience. For me, I was able to digest it quickly, get what I needed and start putting it into practice right away. Some tech books require a heavy time investment by the reader but this one seems to understand that the reader's time is precious. I got a positive impression of the hapi ecosystem and good foundations to get up and running. It took a short amount of time to work through the examples but they all worked well and helped to make what I was learning stick.If you're interested in getting into Node development for the first time or already use Node and need to get a quick but solid overview of hapi, you won't regret choosing this book. You'll finish up with a solid understanding of the hapi project, routing, plugins, testing, authentication and joi validation. There are also some handy tips on production deployment and debugging.
Amazon Verified review Amazon
Pseudonym May 28, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Einleitend ein paar Worte zu meinem Hintergrund, um meine Rezension besser einschätzen zu können:Ich selbst arbeite schon seit einigen Jahren mit JavaScript und mit NodeJS. Habe dabei unter anderem Erfahrung mit dem Framework Express gesammelt und bin daher mit der Materie ein wenig vertraut.Das Buch gliedert sich in sieben prägnante Kapitel, die die jeweilige Thematik kurz und informativ abdecken.Neben dem üblichen einleitenden Kapitel, das die Prinzipien von Hapi beschreibt und einen schönen Einstieg in die Thematik bietet, wird in den beiden folgenden Kapiteln gleich richtig interessant. Der Autor erläutert ausführlich das Erstellen und Konfigurieren von Routes, ohne dabei zu weit und zu tief vorzugreifen. So wird die Validierung nur kurz angesprochen aber nicht weiter vertieft. Die Inhalte der jeweiligen Kapitel lassen sich ja dem "Blick ins Buch" entnehmen. Insgesamt wird auf guten 130 Seiten eine erstaunliche Bandbreite abgedeckt, ohne mit Informationen überschwemmt zu werden:- Plugins- Testing- Validierung- Authentifizierung- "Pro" Tipps zum Thema "Production Mode"Ich muss ehrlich zugeben, dass ich bisher von so recht dünnen Büchern oft enttäuscht war, aber John hat einen tollen Job gemacht.Einen besseren Einstieg in das Thema Hapi finden Sie kaum woanders. Der Autor steht zudem mit Rat und Tat per Twitter zur Seite, sollten Fragen auftauchen, die im Buch nicht geklärt werden können. Dieser Service verdient noch einen weiteren Stern! :)
Amazon Verified review Amazon
Ayyan Nov 15, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a great book as an introduction to hapi.js. A little on the thin side, and one needs to supplement this with all the online material available.
Amazon Verified review Amazon
Logalo Dec 14, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I have found myself skipping many parts of the book after I found out that it is high level introduction to hapi.Although it is well written, it doesn't stand many tutorials on the web which thorough examples and explanations.
Amazon Verified review Amazon
Ganesh A Hegde Jul 03, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
If you are looking out to start with hapi.js then this book will not help you much. Although it does provide some helpful tips, the subject matter is not presented systematically which deters the reader from progressively learning the framework (hapi.js). A few concepts are sprinkled here and there and it's left to the reader to complete the puzzle. There are large number of references (in the Kindle version) linking to the hapi.js documentation on the net. Also in many places, the author mentions new concepts without explaining, leaving his audience lost. Overall, the content matter is not organized for a beginner to quickly understand the framework to use it effectively in his / her next web project. The book does a poor job in developing the subject and given an option I would ask for a refund.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.