Getting Started with hapi.js
By John Brett
()
About this ebook
Build well-structured, testable applications and APIs using hapi.js
About This Book- 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
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
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.
Style and approachThis book takes a step-by-step approach to building an application or web server using hapi.js though examples.
John Brett
John Brett is retired faculty in the Department of Anthropology, University of Colorado Denver with a research focus on global and local food systems, food security and food justice.
Related to Getting Started with hapi.js
Related ebooks
Getting Started with hapi.js Rating: 5 out of 5 stars5/5Building a Web Application with PHP and MariaDB: A Reference Guide Rating: 0 out of 5 stars0 ratingsBeginning PHP: Master the latest features of PHP 7 and fully embrace modern PHP development Rating: 0 out of 5 stars0 ratingsAdvanced Express Web Application Development: For experienced JavaScript developers this book is all you need to build highly scalable, robust applications using Express. It takes you step by step through the development of a single page application so you learn empirically. Rating: 0 out of 5 stars0 ratingsPHP 7 Programming Blueprints: Rethink PHP Rating: 0 out of 5 stars0 ratingsJavaScript and JSON Essentials: Build light weight, scalable, and faster web applications with the power of JSON, 2nd Edition Rating: 0 out of 5 stars0 ratingsImplementing OpenShift Rating: 0 out of 5 stars0 ratingsWebpack 5 Up and Running: A quick and practical introduction to the JavaScript application bundler Rating: 0 out of 5 stars0 ratingsLearning Bootstrap Rating: 1 out of 5 stars1/5Opa Application Development: A rapid and secure web development framework to develop web applications quickly and easily in Opa Rating: 0 out of 5 stars0 ratingsMastering Bootstrap 4: Master the latest version of Bootstrap 4 to build highly customized responsive web apps, 2nd Edition Rating: 0 out of 5 stars0 ratingsLearn WebAssembly: Build web applications with native performance using Wasm and C/C++ Rating: 0 out of 5 stars0 ratingsFull Stack FastAPI, React, and MongoDB: Fast-paced web app development with the FARM stack Rating: 0 out of 5 stars0 ratingsExpress Web Application Development Rating: 3 out of 5 stars3/5Mastering PHP Design Patterns Rating: 0 out of 5 stars0 ratingsRust High Performance: Learn to skyrocket the performance of your Rust applications Rating: 0 out of 5 stars0 ratingsInstant OSGi Starter Rating: 0 out of 5 stars0 ratingsMastering C++ Multithreading Rating: 0 out of 5 stars0 ratingsMastering Flask Web Development: Build enterprise-grade, scalable Python web applications, 2nd Edition Rating: 0 out of 5 stars0 ratingsMastering Sass Rating: 0 out of 5 stars0 ratingsMastering Python Design Patterns Rating: 0 out of 5 stars0 ratingsASP.NET Core 2 and Angular 5: Full-Stack Web Development with .NET Core and Angular Rating: 4 out of 5 stars4/5Beginning React: Simplify your frontend development workflow and enhance the user experience of your applications with React Rating: 0 out of 5 stars0 ratingsHands-on Testing with PHPUnit How-to: A practical guide to getting started with PHPUnit to improve code quality Rating: 0 out of 5 stars0 ratingsDistributed Computing in Java 9 Rating: 0 out of 5 stars0 ratings
Computers For You
Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5Storytelling with Data: Let's Practice! Rating: 4 out of 5 stars4/5Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Data Analytics for Beginners: Introduction to Data Analytics Rating: 4 out of 5 stars4/5Algorithms to Live By: The Computer Science of Human Decisions Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5The Alignment Problem: How Can Machines Learn Human Values? Rating: 4 out of 5 stars4/5Narrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5Get Into UX: A foolproof guide to getting your first user experience job Rating: 4 out of 5 stars4/5The Unaccountability Machine: Why Big Systems Make Terrible Decisions - and How The World Lost its Mind Rating: 0 out of 5 stars0 ratingsPython for Finance Cookbook: Over 50 recipes for applying modern Python libraries to financial data analysis Rating: 0 out of 5 stars0 ratingsBlack Holes: The Key to Understanding the Universe Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5How Do I Do That In InDesign? Rating: 5 out of 5 stars5/5Python for Beginners: A Crash Course to Learn Python Programming in 1 Week Rating: 0 out of 5 stars0 ratingsAdvances in Financial Machine Learning Rating: 5 out of 5 stars5/5Learn Algorithmic Trading: Build and deploy algorithmic trading systems and strategies using Python and advanced data analysis Rating: 0 out of 5 stars0 ratingsDjango Building Dynamic Website With Django : A Complete Step By Step Guide To Learn to Build Modern Web Application with a Python Rating: 0 out of 5 stars0 ratingsArtificial Intelligence: The Complete Beginner’s Guide to the Future of A.I. Rating: 4 out of 5 stars4/5Blender 3D Basics Beginner's Guide Second Edition Rating: 5 out of 5 stars5/5Learn SAP MM in 24 Hours Rating: 0 out of 5 stars0 ratingsDeep Learning with PyTorch Rating: 5 out of 5 stars5/5ITIL® 4 Essentials: Your essential guide for the ITIL 4 Foundation exam and beyond, second edition Rating: 5 out of 5 stars5/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5
Reviews for Getting Started with hapi.js
0 ratings0 reviews
Book preview
Getting Started with hapi.js - John Brett
Table of Contents
Getting Started with hapi.js
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Introducing hapi.js
Node.js – a prerequisite to learning hapi.js
The hapi philosophy versus other frameworks
Building value, not infrastructure
Configuration is better than code
Separation of business logic from the transport layer
Open source and community-centric
Ecosystem
Small modules
Summarizing hapi
Creating our first hapi.js server
Installing hapi
Our first hapi server
hapi plugins
hapi configuration
The hapi style guide
Summary
2. Adding Functionality by Routing Requests
Server routing
Route configuration
Method
Path
Description
Validate
Pre
Handler
Cache
Route configuration summary
hapi routing algorithm
hapi request life cycle
Extending request life cycle events
hapi request object
The reply interface
Custom handlers
Serving static files with inert
Serving templates with vision
Vision configuration
Engines
Paths
compileMode
Vision summary
Summary
3. Structuring Your Codebase with Plugins
Structuring applications
hapi plugins
Encapsulating functionality within plugins
Plugin options
Exposing and consuming plugins
Managing plugin dependencies
Exposing sandboxed functionality
Combining plugins
The hapi plugin ecosystem
Authentication
Documentation generation
Logging
Utilities
Composing applications from plugins
Summary
4. Adding Tests and the Importance of 100% Code Coverage
Why is the importance of testing overlooked?
The benefits and importance of testing code
Introducing hapi's testing utilities
Installing lab and code
Local versus global modules
Our first test script
Testing approaches
Testing hapi applications with lab
Code coverage
Linting
Summary
5. Securing Applications with Authentication and Authorization
Authentication
Configuring authentication
Cookie authentication
Third-party authentication
Authentication summary
Authorization
Summary
6. The joi of Reusable Validation
An introduction to validation
Introduction to joi
Validating hapi routes with joi
Validating route responses
Documentation generation
Summary
7. Making Your Application Production Ready
Persisting data
MongoDB
The 'M' in MVC
Introducing caching
Server methods
Caching with server methods
Introducing logging
Debugging applications
The console
The Node debugger
The debug mode in hapi
Profiling heapdumps
TV
Debugging summary
General production advice
Further learning
Getting started with hapi.js GitHub repo
Hapijs.com
Makemehapi
The hapi community
The hapi discussion repo
Stack Overflow
hapi Gitter channel
@hapijs on Twitter
Read the code!
Summary
Index
Getting Started with hapi.js
Getting Started with hapi.js
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2016
Production reference: 1060416
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-818-2
www.packtpub.com
Credits
Author
John Brett
Reviewer
Jan Lehnardt
Acquisition Editor
Reshma Raman
Content Development Editor
Mehvash Fatima
Technical Editor
Dhiraj Chandanshive
Copy Editor
Sonia Mathur
Project Coordinator
Kinjal Bari
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Production Coordinator
Melwyn Dsa
Cover Work
Melwyn Dsa
Foreword
hapi is a toolkit for web applications (and other HTTP servers) built by people with twice my experience and at least 10 times the smarts. They got the right team together and managed to work with the freedom to get it right this one last time—and they delivered.
hapi is also built by people who understand how to create, foster, and maintain a healthy and inclusive open source community, manage a responsible yet speedy release process, and be all around lovely people. If you are an end user or want to start contributing to the hapi ecosystem, you'll have great fun on your way with the clever technology and, even more so, with the great people.
From the first examples in the first chapter that you work through on your own to a fullfledged system that a large team can work on productively without stepping on each other's toes, Getting Started with hapi.js takes you on the journey to master everything you need to build everything from a hobby project to the most popular site on the Web.
The third step of my usual process
of working with hapi is this: loving hapi even more.
I know you will, too.
Jan Lehnardt
CEO, neighbourhood.ie
About the Author
John Brett is a software engineer passionate about new technologies, open source, and building useful software while travelling the world. Starting out in Ireland with a degree in Computer Science and Software Engineer, he went on to join IBM through their premier internship Extreme Blue, later working on collaboration software as part of IBM's Software Group. There, John mainly worked with PHP and JavaScript, only working with Node.js in his spare time.
Later in his career, John moved to a growing SAAS company called D4H Technologies. As a lead engineer there, he developed tools to aid emergency response teams globally, all from a lighthouse in Dublin, Ireland. Here, John got more exposure to Node.js, leading D4H's first venture into Node using hapi.js, later joining the hapi.js core team
About the Reviewer
Jan Lehnardt is a developer and business person from Berlin, Germany. He is the Vice President of Apache CouchDB (http://couchdb.apache.org), the database that syncs at the Apache Software Foundation, and a co-inventor of Hoodie (http://hood.ie), the web app framework for frontend developers. Jan is the cofounder and CEO of Neighbourhoodie Software, a product and support company based on Hoodie, CouchDB, and general web-nerdery in Berlin. They are also behind http://greenkeeper.io, a service that sends you a pull request when any of your npm dependencies get an update. In his spare time, Jan co-organises JSConf EU, Europe's favorite JavaScript conference.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
eBooks, discount offers, and morehttps://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
Node.js has become one of the most exciting development platforms in recent times. Combined with the largest package ecosystem in the world, npm, it has become a game changer in enabling higher developer productivity strides in improved application performance and a more enjoyable developer experience overall, which has lead to widespread industry adoption.
This book is focused on hapi.js, which is a rich Node.js framework for building applications and services with the goal of enriching the development experience further. It aims to increase your productivity by providing the tools you need when you want them and getting out of the away when you don't.
Developed by the talented team at Walmart Labs to handle the pressures of the Black Friday traffic, the busiest day of online retail on the calendar, it is proven at scale and has since seen wider adoption, participation, and collaboration from the wider community. Its growing adoption can be put down to how easy it is to use and get started with along with its proven stability.
The Node.js programming paradigm is quite different to other server-side technologies, and as such, it can be common for developers to get stuck on design and programming problems, such as dealing with the asynchronous nature of JavaScript and structuring an application as it grows. This is where hapi.js excels; it enables developers to focus on writing reusable business logic instead of losing time focusing on building application infrastructure without obscuring important implementation details.
While it was originally built as a framework focused toward the rapid development of RESTful APIs, thanks to its fantastic ecosystem, it has grown into a fully-fledged framework suited to building static file servers, websites, and web applications with excellent support for building real-time applications added more recently.
Due to the modular plugin approach it provides, it allows an easier collaboration between teams in larger enterprise environments as well as an easy point of integration for third-party libraries.
If you plan to use hapi.js in your next project, whether it be a side project, work project, or open source project, this book seeks to give you an excellent point at which to get started and solidify any knowledge you might have if you have used Node or hapi.js before.
What this book covers
Chapter 1, Introducing hapi.js, serves as an introduction to hapi.js and some prerequisite learning of Node.js. It explains what hapi.js is, who created it, why it needs to exist, and how to create a simple hapi.js server.
Chapter 2, Adding Functionality by Routing Requests, is the beginning of your journey of building applications with hapi.js. It will cover some basics, such as routing and building APIs, websites, and applications with hapi.js, and will also cover some differences in design compared to other Node.js-based frameworks.
Chapter 3, Structuring Your Codebase with Plugins, introduces the plugin API in hapi.js, which is one of its core features. It will walk you through how to simplify an application structure gracefully using plugins and also cover server orchestration using modules from the hapi.js ecosystem.
Chapter 4, Adding Tests and the Importance of 100% Code Coverage, explores the importance of adding tests to an application. It will introduce you to some of the testing tools available in the hapi.js ecosystem and also guide you toward getting 100% code coverage with your tests.
Chapter 5, Security Applications with Authentication and Authorization, takes a deep dive into how authentication works in hapi.js with practical examples of different authentication protocols, including social logins. It also demonstrates scopes and how to use them to add permission levels to your applications.
Chapter 6, The joi of Reusable Validation, deals with the topic of validation in applications using the joi validation library from the hapi.js ecosystem. It covers how to validate objects and route configurations and how to reuse this to generate documentation for applications.
Chapter 7, Making Your Application Production Ready, covers multiple topics to leave you ready to build your first application, such as integrating popular databases and adding caching and logging to applications to help scale an application as well as give it visibility when running in a production environment. It also covers a variety of other sources to continue learning more about hapi.js.
What you need for this book
To try out the examples shown in this book, you will need a working installation of Node.js version 4.x or greater, as well as npm. You will need to be somewhat familiar with the terminal in order to launch applications and install modules from npm. You will also need an editor to modify the code and a browser to view your applications running.
Who this book is for
This book is for a developer with some JavaScript knowledge, with or without Node.js experience, looking to build their first applications or even just learn more about a best-in-class framework to build APIs and applications: hapi.js.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: This creates a directory called hapi-hello, and makes it the current directory.
A block of code is set as follows:
validate: {
headers: true,
params: {
userId: Joi.string().min(4).max(40).required()
},
query: false
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
validate: {
headers: true,
params: {
userId: Joi.string().min(4).max(40).required()
},
query: false
}
Any command-line input or output is written as follows:
$ npm install hapi-swagger inert vision
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: If you navigate to this URL, you should have Hello World returned to you.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your