npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-version-api

v2.0.6

Published

Middleware for versioning routes/APIs in Express.js using semantic versioning like ^1.0 or ~1.2.

Downloads

297

Readme

express-version-api

npm version npm downloads Build Status License: MIT

Version-aware middleware for Express.js APIs with semantic version matching.

Why use this

  • Routes requests by semantic version (exact, ~, ^).
  • Supports extraction from header, query, path, or custom function.
  • Handles missing or unmatched versions with configurable fallback strategies.
  • Exposes req.versionInfo metadata for observability and debugging.
  • Fully typed for TypeScript projects.

Installation

npm

npm install express-version-api

JSR

deno add jsr:@braian-quintian/express-version-api

Requirements:

  • Node.js >= 18
  • Express >= 4

Quick Start

import express from 'express';
import { versioningMiddleware } from 'express-version-api';

const app = express();

app.get(
  '/api/users',
  versioningMiddleware({
    '^1': (_req, res) => res.json({ version: '1.x', users: [] }),
    '^2': (_req, res) => res.json({ version: '2.x', users: [], meta: { total: 0 } }),
    '3.0.0': (_req, res) => res.json({ version: '3.0.0', users: [], paging: null }),
  })
);

app.use((error, _req, res, _next) => {
  res.status(500).json({ error: error.message });
});

Request examples:

curl -H "Accept-Version: 1.2.0" http://localhost:3000/api/users
curl -H "Accept-Version: 2.5.1" http://localhost:3000/api/users
curl -H "Accept-Version: 3.0.0" http://localhost:3000/api/users

Import Modes

ESM (default + named):

import versioningMiddleware, { parseVersion } from 'express-version-api';

CommonJS (named only):

const { versioningMiddleware, parseVersion } = require('express-version-api');

Version Matching Rules

Supported handler keys:

  • Exact: 1.2.3
  • Caret: ^1, ^1.2, ^1.2.3
  • Tilde: ~1.2, ~1.2.3

Matching priority when multiple handlers match:

  1. Exact
  2. Tilde
  3. Caret

Semantics:

  • Exact: must match the same major.minor.patch.
  • Tilde (~): same major and minor, patch must be >= requested patch.
  • Caret (^): semver-compatible range.
  • Caret with 0.x follows strict semver-compatible behavior.

Examples:

  • ^1.2.3 matches 1.2.3, 1.3.0, 1.9.9, but not 2.0.0.
  • ^0.2.3 matches 0.2.3 to 0.2.x, but not 0.3.0.
  • ~2.1.4 matches 2.1.4 to 2.1.x, but not 2.2.0.

How Version Extraction Works

The middleware resolves version in this order:

  1. req.version if already set by upstream middleware (source = custom)
  2. Configured extraction sources in order (extraction.sources)

Default source order:

  1. Header: accept-version
  2. Query: v

You can configure header, query, path, and custom extractors.

versioningMiddleware(
  {
    '^1': v1Handler,
    '^2': v2Handler,
  },
  {
    extraction: {
      sources: ['header', 'query', 'path', 'custom'],
      header: { name: 'x-api-version' },
      query: { name: 'version' },
      path: { pattern: /\/api\/v(\d+(?:\.\d+)?(?:\.\d+)?)\// },
      custom: (req) => (req.hostname.startsWith('v2.') ? '2.0.0' : undefined),
    },
  }
);

Fallback Strategies

Fallback is used when no handler matches, and also when version is missing with requireVersion: false.

  • none: respond with VERSION_NOT_FOUND.
  • latest: execute the handler with the highest available version.
  • default: execute defaultHandler if provided, otherwise fallback to latest.
versioningMiddleware(handlers, {
  fallbackStrategy: 'default',
  defaultHandler: (_req, res) => {
    res.status(200).json({ fallback: true });
  },
});

Error Handling

Error codes emitted by the middleware:

  • MISSING_VERSION
  • INVALID_VERSION_FORMAT
  • VERSION_NOT_FOUND
  • INVALID_CONFIGURATION
  • INVALID_HANDLER

Default status codes:

  • Missing version: 422
  • Version not found: 422
  • Invalid version format: 400

Default response shape:

{
  "error": "VERSION_NOT_FOUND",
  "message": "No handler found for the requested API version",
  "requestedVersion": "99.0.0",
  "availableVersions": ["^1", "^2"]
}

Configure custom messages/statuses and override handling via onError:

versioningMiddleware(handlers, {
  errorResponse: {
    missingVersionStatus: 400,
    missingVersionMessage: 'Version header is required',
    versionNotFoundMessage: (version) => `Version ${version} is not supported`,
    onError: (error, _req, res) => {
      if (error.code === 'INVALID_VERSION_FORMAT') {
        res.status(400).json({ code: error.code, detail: error.message });
        return true;
      }
      return false;
    },
  },
});

Request Metadata (req.versionInfo)

When attachVersionInfo is true, the middleware adds:

{
  requested: string;
  matched: string;
  source: 'header' | 'query' | 'path' | 'custom';
}

Notes:

  • source preserves the real extraction source, including fallback scenarios.
  • When no version was provided and fallback is used, versionInfo is not attached because requested is undefined.

Runtime Defaults

{
  extraction: {
    sources: ['header', 'query'],
    header: { name: 'accept-version' },
    query: { name: 'v' },
    path: { pattern: /\/v(\d+(?:\.\d+)?(?:\.\d+)?)\// },
    custom: undefined
  },
  errorResponse: {
    missingVersionStatus: 422,
    versionNotFoundStatus: 422,
    missingVersionMessage: 'API version is required',
    versionNotFoundMessage: 'No handler found for the requested API version',
    includeRequestedVersion: true,
    onError: undefined
  },
  fallbackStrategy: 'default',
  defaultHandler: undefined,
  validateHandlers: true,
  attachVersionInfo: true,
  requireVersion: true
}

Public API

Main middleware:

  • versioningMiddleware

Error helpers:

  • VersioningError
  • createMissingVersionError
  • createVersionNotFoundError
  • createInvalidVersionFormatError
  • createInvalidHandlerError
  • createInvalidConfigurationError
  • isVersioningError
  • hasErrorCode

Version utilities:

  • parseVersion
  • parseVersionRange
  • versionSatisfies
  • compareVersions
  • findLatestVersion
  • isValidVersion
  • isValidVersionRange
  • normalizeVersion

Config export:

  • DEFAULT_CONFIG

Breaking Changes (v2)

  • Removed legacy createVersionMiddleware API.
  • CommonJS default export was removed; CJS must use named imports.

Development

npm install
npm run validate

Main scripts:

  • npm run typecheck
  • npm run lint
  • npm run format:check
  • npm run test
  • npm run test:coverage
  • npm run build
  • npm run test:types

License

MIT