← Back to hapijs/hapi

How to Deploy & Use hapijs/hapi

Hapi.js Deployment and Usage Guide

Prerequisites

  • Node.js: Version 12.20 or higher (as required by Hapi.js dependencies)
  • npm: Version 6.14 or higher (comes with Node.js)
  • Operating System: Any OS that supports Node.js (Linux, macOS, Windows)
  • Git: For cloning the repository

Installation

Clone the Repository

git clone https://github.com/hapijs/hapi.git
cd hapi

Install Dependencies

npm install

Run Tests (Optional)

npm test

Configuration

Environment Variables

Hapi.js doesn't require specific environment variables for basic operation, but you may need to configure:

  • NODE_ENV: Set to development, production, or test
  • PORT: Default port for your application (typically 3000)
  • HOST: Host address (typically localhost or 0.0.0.0)

Basic Server Configuration

Create a new file server.js in your project root:

'use strict';

const Hapi = require('@hapi/hapi');

const init = async () => {
    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return 'Hello, world!';
        }
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

Build & Run

Development Mode

node server.js

Or use nodemon for automatic restarts:

npm install --save-dev nodemon
npx nodemon server.js

Production Mode

NODE_ENV=production node server.js

Using PM2 for Production

npm install -g pm2
pm2 start server.js --name "hapi-app"
pm2 startup
pm2 save

Deployment

Platform Options

1. Heroku

# Install Heroku CLI
npm install -g heroku

# Login and create app
heroku login
heroku create your-app-name

# Deploy
git push heroku main

Create Procfile:

web: node server.js

2. Docker

Create Dockerfile:

FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Build and run:

docker build -t hapi-app .
docker run -p 3000:3000 hapi-app

3. AWS Elastic Beanstalk

# Install EB CLI
pip install awsebcli --upgrade --user

# Initialize and deploy
eb init your-app-name
eb create your-environment
eb deploy

4. DigitalOcean App Platform

Push to GitHub and connect to DigitalOcean App Platform, or use the CLI:

doctl apps create --spec app.yaml

Troubleshooting

Common Issues

1. Port Already in Use

Error: listen EADDRINUSE :::3000

Solution: Kill the process using the port or change the port number:

# Find process
lsof -i :3000

# Kill process
kill -9 <PID>

# Or change port in server.js
port: 3001

2. Module Not Found

Error: Cannot find module '@hapi/hapi'

Solution: Ensure dependencies are installed:

npm install

3. Node Version Compatibility

Error: Invalid version

Solution: Check Node.js version compatibility:

node --version
npm ls @hapi/hapi

4. Memory Issues in Production

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed

Solution: Increase memory limits or optimize your application:

node --max-old-space-size=4096 server.js

5. CORS Issues

If you encounter cross-origin resource sharing problems:

const server = Hapi.server({
    port: 3000,
    host: 'localhost',
    routes: {
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    }
});

Debug Mode

Enable debug logging:

DEBUG=hapi* node server.js

Or in code:

server.events.on('request', (request, event, tags) => {
    if (tags.error) {
        console.error(event);
    }
});