Setting Up a Hapi.js Development Environment with ServBay
Hapi.js is a powerful and flexible Node.js framework ideal for building applications and APIs. ServBay provides Node.js developers with a convenient local development environment integrated with Node.js runtime, multiple databases, and configurable web server features. This guide walks you through creating and running a Hapi.js project using ServBay, configuring its Websites feature for access, and connecting to ServBay’s built-in databases.
What is Hapi.js?
Hapi.js is a powerful and flexible Node.js framework developed by Walmart Labs for building applications and services. Renowned for its robust plug-in system, configuration-driven approach, and built-in security features, it enables developers to efficiently create high-performance, maintainable web applications and APIs.
Key Features and Benefits of Hapi.js
- Plugin System: Hapi.js boasts a powerful and easy-to-use plugin system, enabling simple extension of framework features or organizing app logic into reusable modules.
- Configuration-Driven: Advocates for a configuration-first development style, where detailed configuration options define behavior for routing, validation, caching, and more.
- Input Validation: Bundled with the robust Joi library, offering declarative data validation to ensure data integrity and security.
- Rich Ecosystem: Backed by a vibrant community and a wealth of official and third-party plugins, covering common needs like authentication, authorization, caching, logging, and more.
- Security: Built-in security features help prevent common web vulnerabilities, including input validation and CORS control.
- Logging and Debugging: Provides detailed request lifecycle logs and helpful debugging tools.
By using Hapi.js, developers can focus on implementing business logic while delegating core HTTP handling, routing, validation, and security concerns to the framework.
Creating a Hapi.js Project with ServBay
This section guides you through using ServBay’s Node.js environment to create and run a basic Hapi.js project, and accessing it through ServBay’s Websites feature (reverse proxy).
Prerequisites
Before you begin, ensure that:
- You have successfully installed ServBay on macOS.
- You have enabled the Node.js package in the ServBay app. You can find and enable Node.js in the "Packages" tab of the ServBay control panel.
- You are familiar with basic terminal operations and npm (Node.js package manager).
Creating a Hapi.js Project
Initialize Project Directory
Open your terminal and navigate to the ServBay recommended web root at
/Applications/ServBay/www
. Create a new project folder (e.g.servbay-hapi-app
) in this directory and enter it:bashcd /Applications/ServBay/www mkdir servbay-hapi-app cd servbay-hapi-app
1
2
3Initialize a Node.js Project
Inside the project directory, use npm to initialize a Node.js project:
bashnpm init -y
1This generates a
package.json
file in your project root.Install Hapi.js Dependency
Use npm to install the Hapi.js core library:
bashnpm install @hapi/hapi
1This adds
@hapi/hapi
to your project dependencies.Create Application Entry File
In your project root, create a file named
server.js
and add the following code to create a simple Hapi.js server:javascript'use strict'; // Enable strict mode const Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: process.env.PORT || 3000, // Listen on port 3000 by default, or as specified by the PORT environment variable host: 'localhost' // Listen on the local loopback address }); // Define a simple root route server.route({ method: 'GET', path: '/', handler: (request, h) => { return 'Hello from Hapi.js powered by ServBay!'; } }); // Start the server await server.start(); console.log('Server running on %s', server.info.uri); }; // Handle unhandled Promise Rejections process.on('unhandledRejection', (err) => { console.error(err); process.exit(1); // Exit the process }); // Call the init function to start the app init();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33This code creates a Hapi server that listens on
localhost
at the specified port (default 3000) and sets up a simple GET handler for the root path/
.
Switch to Development Mode and Configure ServBay Website
During development, you can run your Node.js app directly and use ServBay’s reverse proxy feature to map it to a custom domain, making it accessible via your browser with ServBay’s SSL certificates.
Run the Hapi.js Development Server
In the terminal, ensure you’re in the
servbay-hapi-app
project directory, then use thenode
command to runserver.js
. To coordinate with ServBay’s reverse proxy, specify a particular port, such as8585
:bashPORT=8585 node server.js
1The server will start and display the listening URI, e.g.,
Server running on http://localhost:8585
. Leave this terminal window open, as the server needs to be running.Configure a Website (Reverse Proxy) in ServBay
Open the ServBay application. Switch to the "Websites" tab and click the "+" button in the lower left to add a new website.
- Name:
ServBay Hapi Dev
(Customizable, for identification in the list) - Domain:
servbay-hapi-dev.servbay.demo
(It’s recommended to use the.servbay.demo
suffix to avoid real domain conflicts and leverage ServBay’s local CA certificate) - Type: Choose
Reverse Proxy
- Proxy to:
- Protocol:
http
- IP Address:
127.0.0.1
(Since Node.js is running on the local loopback) - Port:
8585
(Matches the PORT variable used when runningnode server.js
)
- Protocol:
Click "Add" to complete the setup. ServBay will automatically configure the web server (such as Caddy or Nginx) to proxy requests from
https://servbay-hapi-dev.servbay.demo
tohttp://127.0.0.1:8585
. ServBay will also generate and trust an SSL certificate for.servbay.demo
domains (via the ServBay User CA), letting you securely access your app over HTTPS locally.For detailed ServBay website configuration steps, refer to the ServBay Website Configuration Guide.
- Name:
Access Your Development Hapi.js App
Open your web browser and visit your configured domain:
https://servbay-hapi-dev.servbay.demo
. You should see the message, "Hello from Hapi.js powered by ServBay!".Now, any changes you make to the
server.js
file (commonly with hot-reloading tools like nodemon) will be instantly reflected in the browser through ServBay’s reverse proxy.
Example Deployment for Production
For production, you’ll want more robust process management (like PM2) and different configurations. Here’s a simple example, showing how to run on a different port and access via ServBay reverse proxy:
Run the Hapi.js Production Server
Assume you run your app on a different port (e.g.,
8586
) and with the production environment configuration:bashPORT=8586 NODE_ENV=production node server.js
1(Note: In real production, you should use PM2 or other tools to manage your Node.js process for stability and auto-restart. ServBay also supports PM2 integration.)
Configure a Production Website (Reverse Proxy) in ServBay
In ServBay’s "Websites" tab, click "+" to add another website:
- Name:
ServBay Hapi Prod
- Domain:
servbay-hapi-prod.servbay.demo
- Type:
Reverse Proxy
- Proxy to:
- Protocol:
http
- IP Address:
127.0.0.1
- Port:
8586
- Protocol:
Click "Add".
- Name:
Access the Production Version of Your Hapi.js App
Open your browser and visit
https://servbay-hapi-prod.servbay.demo
. You’ll see the same output as in development mode (unless your code behaves differently based onNODE_ENV
), but now it’s running with production configuration and port.
With ServBay’s Websites feature, you can easily manage multiple local development or simulated production domains and map them to Hapi.js (or other Node.js) app instances running on different ports.
Connecting to ServBay Databases
ServBay comes with built-in support for multiple database systems, including MySQL, MariaDB, PostgreSQL, MongoDB, and Redis. This section demonstrates how to connect to these databases from your Hapi.js project.
Important: Before connecting to a database, ensure you’ve enabled the desired database package in the "Packages" tab of ServBay and started the corresponding database service. You can check the running status in the ServBay control panel.
Default ServBay database users and passwords:
- MySQL/MariaDB: Username
root
, passwordpassword
- PostgreSQL: Username
user
, passwordpassword
- MongoDB: No authentication by default
- Redis: No authentication by default
Note: For security, it is strongly recommended that you change the default passwords in ServBay, especially for non-local usage. You can easily reset root passwords for MySQL, MariaDB, and PostgreSQL using ServBay’s tools. See the Database Password Reset Guide.
Below are sample code snippets for connecting to each type of database. Be sure to install the respective client package via npm first.
Connect to MySQL
Install the MySQL client library:
bashnpm install mysql2 # or mysql
1Example connection code using
mysql2
:javascriptconst mysql = require('mysql2'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', // ServBay default username password: 'password', // ServBay default password database: 'servbay_hapi_app' // Replace with your database name }); connection.connect(err => { if (err) { console.error('Error connecting to MySQL: ' + err.stack); return; } console.log('Connected to MySQL as id ' + connection.threadId); }); // Close connection when finished // connection.end();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19Connect to MariaDB
Install the MariaDB client library:
bashnpm install mariadb
1Example connection code:
javascriptconst mariadb = require('mariadb'); const pool = mariadb.createPool({ host: 'localhost', user: 'root', // ServBay default username password: 'password', // ServBay default password database: 'servbay_hapi_app', // Replace with your database name connectionLimit: 5 // Pool size }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB"); // conn.query(...) execute queries conn.release(); // Release connection back to pool }) .catch(err => { console.error("Not connected to MariaDB due to error: " + err); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18Connect to PostgreSQL
Install the PostgreSQL client library:
bashnpm install pg
1Example connection code:
javascriptconst { Pool } = require('pg'); const pool = new Pool({ user: 'user', // ServBay default username host: 'localhost', database: 'servbay_hapi_app', // Replace with your database name password: 'password', // ServBay default password port: 5432, // Default PostgreSQL port }); pool.connect((err, client, done) => { if (err) { console.error('Error connecting to PostgreSQL: ', err); return; } console.log('Connected to PostgreSQL'); client.query('SELECT NOW()', (err, res) => { done(); // Release client connection if (err) { console.error('Error executing query', err.stack); } else { console.log('PostgreSQL current time:', res.rows[0].now); } }); }); // Pool will close automatically on app exit // pool.end();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27Connect to MongoDB
Install the MongoDB client library:
bashnpm install mongoose # or mongodb
1Example connection code (using
mongoose
):javascriptconst mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/servbay-hapi-app', { useNewUrlParser: true, useUnifiedTopology: true, // ServBay's default MongoDB requires no authentication; if you enable auth, add authSource, user, pass // authSource: 'admin', // user: 'your_username', // pass: 'your_password', }) .then(() => console.log('MongoDB connected')) .catch(err => console.error('MongoDB connection error:', err)); // The Mongoose connection stays active during your app's lifecycle // Disconnect: mongoose.connection.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Connect to Redis
Install the Redis client library:
bashnpm install redis
1Example connection code:
javascriptconst redis = require('redis'); // Use default parameters: host: 'localhost', port: 6379 const client = redis.createClient(); client.on('error', function (err) { console.error('Redis Error: ' + err); }); client.on('connect', function () { console.log('Redis client connected'); }); // Connect to the Redis server client.connect(); // For redis v4+ you need to call connect() // Example: Setting and getting key-value // async function exampleRedisUsage() { // await client.set('mykey', 'myvalue'); // const value = await client.get('mykey'); // console.log('Value from Redis:', value); // await client.del('mykey'); // } // exampleRedisUsage(); // Close connection on app exit // client.quit();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
By integrating these connection examples into your Hapi.js app, you can leverage ServBay’s database services in your local development environment.
Summary
ServBay makes setting up a Hapi.js development environment on macOS highly efficient. It delivers a one-stop solution, including easy-to-manage Node.js runtime, a suite of ready-to-use databases, and streamlined local access via the Websites feature (reverse proxy and automatic SSL). By following the steps above, you can swiftly launch your Hapi.js project and take full advantage of ServBay’s robust features to accelerate your development process.