api-express-versioning
v1.0.6
Published
API versioning middleware for Express to avoid duplicating controllers
Downloads
18
Maintainers
Readme
Express API Versioning
A middleware for Express.js to handle API versioning without duplicating controllers.
Installation
npm install api-express-versioning
Features
- Automatic Version Handling: Manage multiple API versions with ease based on folder structure.
- Fallback Mechanism: If a route is not found in the requested version, the middleware will automatically check previous versions (e.g., if
v4
doesn't have a route, it will tryv3
). - Version Headers: Specify the API version via headers using
api-version: v1
. The middleware selects the correct route based on the version provided. - Custom Error Messages: Return customizable error responses when a route is not found.
- No Controller Duplication: Prevents duplicating controller logic across versions. If a specific route is not defined in a version, it reuses the logic from earlier versions automatically.
Folder Structure
Ensure your folder structure follows the pattern below. All version folders should start with the same prefix (e.g., v1
, v2
, etc.).
/src
/controllers
/api
/v1
/v2
/v3
/v4
/v5
/routes
/api
/v1
/v2
/v3
/v4
/v5
index.js
Usage
Set up the versioning middleware in your Express app as shown below:
//FILE - src/routes/api/index.js
const express = require("express");
const versioningMiddleware = require("api-express-versioning");
const router = express.Router();
// App router for versioned APIs
router.use(
"/api",
versioningMiddleware(
__dirname + "/api", // API routes directory
"v", // version routes base directory name - all route folders start with this prefix.
"v1", // default version to fall back to
// Custom error message when a route is not found
{
code: 0,
message: "Route not found.",
}
)
);
module.exports = router;
Example Scenario
If you have 5 API versions (v1
to v5
), pass the desired version via headers with api-version: v4
. If the route is not found in v4
, the middleware will automatically fall back to v3
, continuing until it finds a route or defaults to v1
.
Benefits
- No Controller Duplication: No need to duplicate controller logic across versions. Middleware reuses logic from earlier versions if newer ones don’t have the route.
- Simplified Version Management: Easily manage different API versions using folder structure, reducing codebase complexity.
- Automatic Fallback: Gracefully handles requests by stepping down to previous versions if the route is unavailable in the requested version.