Hapi API Versioning Plugin

2.3.1 · abandoned · verified Tue Apr 21

hapi-api-version is a plugin designed for the Hapi.js framework (v17 onwards) to facilitate API versioning. It allows developers to manage different API versions by supporting versioning via the `Accept` header or a custom header (defaulting to `api-version`). The plugin internally rewrites URLs based on the requested API version, enabling both handler-only versioning and distinct route definitions per version, including separate response schemas. The latest version, 2.3.1, was last published 7 years ago, making it compatible only with older Hapi.js ecosystems (specifically Hapi v17.x). It does not receive active updates for modern Hapi versions (v20+ or v21+), implying a halted release cadence and limited applicability for current Hapi projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a Hapi server, registering the hapi-api-version plugin with basic options, and defining both versioned and unversioned routes. It shows how to access the detected API version from `request.pre.apiVersion` to serve different data based on the client's requested version.

'use strict';

const Hapi = require('@hapi/hapi');
const hapiApiVersion = require('hapi-api-version');

const init = async function () {
    try {
        const server = new Hapi.server({ port: 3000 });
        await server.register({
            plugin: hapiApiVersion,
            options: {
                validVersions: [1, 2],
                defaultVersion: 2,
                vendorName: 'mysuperapi'
            }
        })

        server.route({
            method: 'GET',
            path: '/users',
            handler: function (request, h) {
                const version = request.pre.apiVersion;
                if (version === 1) {
                    return [{ name: 'Peter Miller' }];
                }
                return [{ firtname: 'Peter', lastname: 'Miller' }];
            }
        });

        server.route({
            method: 'GET',
            path: '/loginStatus',
            handler: function (request, h) {
                return { loggedIn: true };
            }
        });

        await server.start();
        console.log('Server running at:', server.info.uri);
    }
    catch (err) {
        console.error('Server startup error:', err);
        process.exit(1);
    }
};

init();

view raw JSON →