Hapi HTTP to HTTPS Redirection

6.0.0 · active · verified Wed Apr 22

hapi-require-https is a Hapi plugin designed to enforce HTTPS for incoming requests, providing automatic HTTP to HTTPS redirection. The current stable version is 6.0.0, which requires Hapi v20 or newer. This plugin primarily operates by default using the `X-Forwarded-Proto` header, making it ideal for applications running behind a reverse proxy (like on Heroku or other PaaS environments). It offers a straightforward API, registering as an `onRequest` lifecycle hook to perform 301 redirects. A key differentiator is its explicit support for proxy environments, configurable via a `proxy` option, which can be set to `false` to redirect based on the actual request protocol instead of the forwarded header. Release cadence typically aligns with major Hapi versions or necessary compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Hapi server and register hapi-require-https, enabling automatic HTTP to HTTPS redirection. It includes a simple route to show the active protocol.

import Hapi from '@hapi/hapi';
import HapiRequireHttps from 'hapi-require-https';

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

    await server.register({
        plugin: HapiRequireHttps,
        options: {
            proxy: true // Default, redirects based on X-Forwarded-Proto
        }
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return `Hello from Hapi! Protocol: ${request.server.info.protocol}. Real protocol: ${request.headers['x-forwarded-proto'] || 'unknown'}`;
        }
    });

    await server.start();
    console.log(`Server running on ${server.info.uri}`);
};

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

init();

view raw JSON →