Creating and Running a Hapi.js Project
What is Hapi.js?
Hapi.js is a powerful and flexible Node.js framework for building applications and services. Created by Walmart Labs, it is renowned for its plugin system and rich features. Hapi.js provides a straightforward way to handle HTTP requests and responses, enabling developers to build high-performance web applications and APIs more efficiently.
Main Features and Advantages of Hapi.js
- Plugin System: Hapi.js has a robust plugin system that allows for easy extension and code reuse.
- Routing System: Offers a flexible and powerful way to define and handle routes.
- Input Validation: Built-in strong input validation to ensure data integrity and security.
- Rich Ecosystem: A wide range of plugins and community support covering common functionality needs.
- Security: Various security features, such as protection against Cross-Site Request Forgery (CSRF) and Cross-Site Scripting (XSS) attacks.
Using Hapi.js helps developers quickly build high-performance and secure web applications and APIs.
Creating and Running a Hapi.js Project using ServBay
In this article, we will use the Node.js environment provided by ServBay to create and run a Hapi.js project. We'll set up the web server using ServBay's 'Host' feature and use a reverse proxy to access the project.
Creating a Hapi.js Project
Initialize the Project
First, ensure you have installed the Node.js environment provided by ServBay. Then, in the suggested website root directory
/Applications/ServBay/www
, create a new Hapi.js project:bashcd /Applications/ServBay/www mkdir servbay-hapi-app cd servbay-hapi-app npm init -y npm install @hapi/hapi
1
2
3
4
5Create Application File
In the project root directory, create a
server.js
file and add the following code:javascriptconst Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: process.env.PORT || 3000, host: 'localhost' }); server.route({ method: 'GET', path: '/', handler: (request, h) => { return 'Hello ServBay!'; } }); await server.start(); console.log('Server running on %s', server.info.uri); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); 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
Entering Development Mode
Run the Development Server
Start the development server and specify the port (e.g., 8585):
bashPORT=8585 node server.js
1This will start a development server locally and expose port 8585.
Configure ServBay Host Reverse Proxy
Use ServBay's 'Host' feature to access the development server via a reverse proxy. In the ServBay 'Host' settings, add a new reverse proxy:
- Name:
My first Hapi.js dev site
- Domain:
servbay-hapi-test.dev
- Host Type:
Reverse Proxy
- IP:
127.0.0.1
- Port:
8585
For detailed setup steps, refer to adding a Nodejs development website.
- Name:
Access Development Mode
Open your browser and visit
https://servbay-hapi-test.dev
to view the project in real time. Due to ServBay’s support for custom domains and free SSL certificates, you will enjoy enhanced security.
Deploying the Production Version
Prepare the Production Environment
Ensure your project can run smoothly in the production environment. Generally, Hapi.js projects do not require specific build steps, but you may need to set some environment variables or perform other configurations.
Run the Production Server
Start the production server and specify the port (e.g., 8586):
bashPORT=8586 NODE_ENV=production node server.js
1Configure ServBay Host Reverse Proxy
Use ServBay's 'Host' feature to access the production server via reverse proxy. In the ServBay 'Host' settings, add a new reverse proxy:
- Name:
My first Hapi.js production site
- Domain:
servbay-hapi-test.prod
- Host Type:
Reverse Proxy
- IP:
127.0.0.1
- Port:
8586
- Name:
Access Production Mode
Open your browser and visit
https://servbay-hapi-test.prod
to view the production version. With ServBay’s custom domains and free SSL certificates, your website will have higher security and credibility.
Database Connection
ServBay provides support for Redis, MariaDB, PostgreSQL, and MongoDB databases. Here are examples of how to connect to these databases.
Connecting to MongoDB
Install
mongoose
:bashnpm install mongoose
1Then, include and connect in your project:
javascriptconst mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/servbay-hapi-app', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.log(err));
1
2
3
4
5Connecting to Redis
Install
redis
:bashnpm install redis
1Then, include and connect in your project:
javascriptconst redis = require('redis'); const client = redis.createClient(); client.on('error', function (err) { console.log('Error ' + err); }); client.on('connect', function () { console.log('Redis client connected'); });
1
2
3
4
5
6
7
8
9
10Connecting to MariaDB
Install
mariadb
:bashnpm install mariadb
1Then, include and connect in your project:
javascriptconst mariadb = require('mariadb'); const pool = mariadb.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_hapi_app' }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB"); conn.release(); //release to pool }) .catch(err => { console.log("Not connected due to error: " + err); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16Connecting to PostgreSQL
Install
pg
:bashnpm install pg
1Then, include and connect in your project:
javascriptconst { Pool } = require('pg'); const pool = new Pool({ user: 'user', host: 'localhost', database: 'servbay_hapi_app', password: 'password', port: 5432, }); pool.connect((err, client, done) => { if (err) throw err; console.log('Connected to PostgreSQL'); done(); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
By following the above steps, you have successfully created and run a Hapi.js project using the features provided by ServBay, and connected to various databases.